问:
Code cleanup methods and/or code coverage tools
I have an application at work, which I started work on about 7 years ago. This was my first engagement in ASP.NET web applications, and coming from a Win32 background I had a hard time adjusting.

All this time, both the project and myself have "matured" and now most parts of it are well defined, properly structured and readable. However, there is a significant piece of it, that is "old junk". By that I mean old obsolete code, that was not working well, or was not properly structured, which has been replaced, but left in the source files instead of being removed. I must note here, that I was not the sole developer, but did most of the coding throughout.

What I want to do, is whenever I have free time at work, to remove the old obsolete and unused code. Are there any techniques/methodologies that I can use/follow in order to do this more efficiently? Any tools perhaps?

EDIT: (clarification based on feedback)
The code I am talking about is not used anywhere, and is not called from anywhere in the project. What I need is way to find out where the code resides, since we are talking about a large codebase. So something in terms of code coverage tools would help. Any suggestions for asp.net projects? (the particular case is in Web Site project form)

答:
The static code analysis tools included with Visual Studio will find code "with no upstream callers".  If you don't want to turn on all of the code analysis rules for your project, look for the following rules to turn on:

CA1811: Avoid uncalled private code (Performance Rules)

CA1812: Avoid uninstantiated internal classes (Performance Rules)

CA1801: Review unused parameters (Usage Rules)

CA1804: Remove unused locals (Performance Rules)

No idea why some are under the Performance category and others under Usage, but these are the rules I'm aware of to find unused code in VS.


问:
Scrum: how to integrate work done by an overachieving developer out of band?
We have a "typical" SCRUM team and we commit to work for a sprint, and also maintain a backlog. Recently we have run into a problem of trying to integrate/handle the work of an overachieving developer doing out of band work (choosing to work outside of the normal working hours/sprint).

To give an example, if the team takes in 50 points of work, let's say that they will complete all that work within the SCRUM framework by the end of the sprint and they and the company is happy. One of the team members decides to work on their own, on a backlog item, on their own free time. They do not check in this work, but instead save it (we use TFS and it is in a shelveset).

How to handle this? A few of the problems ..

During the next sprint this team members says the programming work is 99% done and just needs code review and testing. How do you deal with this in the SCRUM and agile methodology?

Other developers complain about not being involved in design decisions related to these stories, since the work was done out of band.

Our product owner is tempted to pull in this "free" work and the overachieving members is likely doing this on purpose in order to get more features into the product that the team otherwise would not be able to accomplish in the sprint(s). There is a view that this is breaking the "process". Obviously QA, UI and documentation work still need to be done on this work.

I see a lot of discussion about not forcing a SCRUM team to work overtime, but what about a member of the team working above and beyond the expectations put forth during planning and execution of sprints? I would hesitate to reign this person in and say you cannot work extra (cautioning on burn out of course), but at the same time it seems to be causing some issues with certain members of the team (but not all).

How to integrate work done by an overachieving member into the SCRUM and agile process for software development?

答:
Have them also be a teacher

It is great that you have a star developer with the best and most advanced skills in the group.  I would praise and compliment this.  Often such folks are the 'glue' that hold organizations together.

I would view the challenge as 'how to get less experienced developers closer to the productivity of the most advanced developer'.

One great way to do this is to focus on getting the star developer to spend more time teaching, training and guiding the less experienced and slower team members.  I would first discuss this in a 1-to-1 with the star developer so they know what you are doing and why.  Other wise it may be viewed with suspicion as a hidden agenda / poor managment

When you do standups, once or twice a day, if this person runs out of work and others are still doing tasks, look to pair-programming so that she can pair with the junior members and impart her great knowledge and experience.  Make sure to ask the question "does anyone need help? Is anyone looking for a pair?"

You could also find some 'side' work for the best developer for when they are out of work, such as enhancing the toolset being used by all, running a technical book club discussion group or being involved in other organizational projects.

ContentLicense: CC BY-SA 3.0


问:
What are the most used pattern to manage a lot of interconnected parameters?
I recently start to work on an application that drive different measurement device.

Before the user start a measure, she sets the parameters of it.

Actually, considering all measurements type there are 50+ parameters.

The difficulty here is that every settings depends on others for:

Being available

List of available values

so on..

Moreover, some measurement settings depend on previous measure results and settings.

To make it short : we have a lot of stuff that are interconnected.

The actual pattern is to validate everything as soon as a values is changed. It cost a lot (in time) and we are going to add a lot of more parameters : it will break.

We try to implement a pattern where we use ObservableValues and where all parameters register on all values it depend on.

It became hard when the parameters depend on an other reference measure. If the reference change, we have to stop listening on the previous reference and start to listen on the new reference.

Etc...

An other issue is that when we work on our pattern and we had more capabilities (like serialization), or when we had some helper class (like factory), we build big files with 50+ parameters or functions.

Is there any other good pattern or library to do it ?

答:
There are many different ways to approach the updating of such interconnected parameters; I have prior experience with two: For the purposes of this answer I will call them the "centralized" approach and the "decentralized" approach.

In the centralized approach, you have a single "UpdateEverything" function which you have to make sure to invoke every single time you do anything in your entire system which has even the slightest chance of requiring an update.  The advantage of the centralized approach is that it is simple: all the code which implements the updating is in one place, so you can read through it to make sure it is correct. The disadvantages of the centralized approach are that a) the "UpdateEverything" function usually ends up being monstrously long, b) it does all of the updating every single time it gets invoked even though only a few things may have changed and therefore only a few things may really needed to be updated, and c) it tends to be invoked excessively, just so as to reduce the chances of missing an update, so overall, it represents a huge unnecessary overhead.

The decentralized approach is what you have already said you have started working on; it is a lot more involved and it actually requires building some framework before it can be used.  In this approach, each parameter is capable of triggering a "changed" notification, and each parameter has knowledge of every single one of the parameters that it depends on, so that it can register with them to be notified when they change, and thus recompute its own value, possibly triggering its own "changed" notification in turn. The decentralized approach solves all of the problems of the centralized approach, but it is more elaborate and therefore more costly to implement.

A few points to note:

You will need to introduce and primarily make use of some "ReadonlyParameter" interface, which has a "GetValue()" and a "RegisterForChangedEvent()", but no "SetValue()", because it makes no sense to set the value of a parameter which is built to recompute its own value based on the values of other parameters.  "read-only" in this context does not mean that its value may never change, it just means that you may not change its value, though its value may still change due to other reasons, so it makes sense to register with it in order to observe any such changes.

For those parameters that receive values from the outside, you may need to introduce a "StoringParameter" class which "stores" (contains) its own value, implementing the "ReadonlyParameter" interface and also offering a "SetValue()" method.

A parameter that knows how to compute its own value will need to cache that value, so that a) it can respond to "GetValue()" without costly recalculations, and b) it only issues a "Changed" notification when its cached value changes, so as to eliminate unnecessary updates.

A parameter that knows how to compute its own value will generally have a private RecomputeOwnValue() method which gets invoked a) whenever one of the parameters it depends on changes, b) once at the end of its own constructor, so as to compute its initial value. If there is a possibility that a parameter might need to stop depending on a particular parameter and instead start depending on another parameter, then you will need to also invoke RecomputeOwnValue() whenever a dependent parameter is added/removed.

You can create an entire algebra of parameters for frequently used operations.  For example, you can introduce logical AND, OR, XOR etc parameter classes, which know how to recompute their own values as the result of a logical operation on the values of two other boolean parameters that they depend on, you can introduce arithmetic operation parameter classes, doing addition, subtraction, multiplication, division etc., and so on.

You can write simple helper functions that instantiate interconnected parameters in a way that is as convenient as writing expressions.  So, you might have something like this:

d = fob( a, fiddle( b, c ) ) );

Where fob() creates a FobParameter object, and fiddle() creates a FiddleParameter object, so the above expression means that parameter d is a new FobParameter() which happens to depend on two instances of ReadonlyParameter, for which we pass pre-existing parameter a and a new FiddleParameter(), which in turn happens to depend on another two instances of ReadonlyParameter, for which we pass pre-existing parameters b and c.


问:
CMS with unknown data structure
I am looking to build a sports small application, but I would like to build it so other people/organizations could use it as is. These would be separate apps, not one app that caters for all. For example American Football would have the app and Basketball would have their own app, completely separate entities.

The application would need to be specific to their data needs and each organisation's app would need to store different data. But they'd all maintain some commonality, like users, logins, forgotten passwords, signups etc

I can provide a base application for all common storage items and the website functionality. What are the most proven and flexible ways to allow a person/organisation to cater to their data needs and be able to store/manipulate/retrieve custom data with little custom editing of the server side language?

I'm wondering is this a good case for using something like Mongo rather than a traditional RDBMS?

To confirm it's not just turning some fields on or off in tables, but the data will for the most part very user-centric if that helps.

Update

As per Guy's comment, it will be used for coach and player data for each sporting organization. It will all be based around either the coach or player, the full complete differences between sports organizations I wouldn't know at this point, but I know there are differences from people who work in them, for example:

For players and coaches there will be standard data to help identify them and note their names, players height, players weight those kind of metrics. Where it gets more complicated is that the sports have completely different models for qualifications, multiple different streams, with various tiers and sub modules. Normally I'd just look to build an "active" column that could turn the odd field off or on. But It appears that it might be too rudimentary as the models are so different.

答:
Premature generalization?

Have you ever read about The Rule of Three? I think you are trying to generalize a little too soon.

It will all be based around either the coach or player, the full
  complete differences between sports organizations I wouldn't know at
  this point, but I know there are differences from people who work in
  them, for example [...]

It is very tempting to try building a generic framework from scratch, but this is risky. You don't know what are your requirements for American Football, nor the one for Basketball; you don't really know what will be generic and what will be fixed.

It is very hard to guess how to build abstraction with a top-down approach. On the other hand, you don't need to build a complete application before understanding what parts need to be made reusable (e.g. logins). I would suggest to build only one application first, and see how it goes. When you have a basic understanding of the rules governing your domain, when your first application have a minimal set of features that you like, try to see how to make a second one.

Try to write modular code, decouple as much as possible, and refactor so that you don't repeat yourself. When you have enough informations about the differences and the commonalities between your applications, you will be able to refactor sensibly and provide good abstractions.

Custom CMS

You decided to write a custom CMS instead of using one, but you can still look at an existing open-source implementation (Drupal) to see how they manage customizations. See for example the Schema API.

I don't have much experience with CMS, nor Mongo. I don't think you risk much by choosing one approach over another like Mongo or RDBMS: pick the one you are the most familiar with, or the one you want to learn ;-) and make version 1.0 of your application.

Title: CMS with unknown data structure


问:
How to setup build system for unit testing + mocking?
We have a legacy code base in entirely C++. Our build system is CMake. My first stab at unit testing was as follows:

Define a target (LibraryA). This library contains the code to test.

Define a unit test target per CPP test file in LibraryA being tested and link against LibraryA.lib.

Basically the source structure is like so:

```<code>LibraryA/
  Source/
    Utils/
      MyClass.cpp
      MyClass.hpp
      AnotherClass.cpp
      AnotherClass.hpp
    Network/
      Socket.cpp
      Socket.hpp
  Tests/
    Utils/
      TestMyClass.cpp
      TestAnotherClass.cpp
</code>```

What we have here is a mirror structure of the Source directory inside Tests. This structure allows me to use include order trickery at the compiler command line level to prioritize where class headers are found for mocking purposes. Each Test*.cpp file under Tests results in 1 executable. So 1 executable test per class being tested.

The issue is that I'm linking against LibraryA.lib in my test executable. This results in ODR violation because if I want to mock the Socket class, the LibraryA.lib will have already compiled symbols into it. Now I can't mock it without duplicating symbols and the linker will complain.

Overall setting up unit test structure has been a giant pain from the build system perspective when it comes to mocking.

Is there a good solution to this problem? Is my approach to test structure completely wrong?

答: Simple: mock libraries (mocking both .cc and .h files) and be prepared that the same library will be mocked in different ways for different tests.</p>


问:
In git, how to do versioning for a dozen libraries all worked at in parallel
We are doing projects, but we reuse a lot of code between the projects and have lots of libraries that contain our common code. As we implement new projects we find more ways to factor out common code and put it into libraries. The libraries depend on each other, and the projects depend on the libraries. Each project, and all libraries used in that project, need to use the same version of all the libraries they are referring to. If we release a piece of software we will have to fix bugs and maybe add new features for many years, sometimes for decades. We have about a dozen libraries, changes often cut across more than two, and several teams work on several projects in parallel, making concurrent changes to all these libraries.

We have recently switched to git and set up repositories for each library and each project. We use stash as a common repository, do new stuff on feature branches, then make pull requests and merge them only after review.

Many of the issues we have to deal with in projects requires us to do changes across several libraries and the project's specific code. These often include changes of library interfaces, some of which are incompatible. (If you think this sounds fishy: We interface with hardware, and hide specific hardware behind generic interfaces. Almost each time we integrate some other vendor's hardware we run into cases our current interfaces did not anticipate, and so have to refine them.) For example, imagine a project P1 using the libraries L1, L2, and L3. L1 also uses L2 and L3, and L2 uses L3 as well. The dependency graph looks like this:

```<code>   <-------L1<--+
P1 <----+  ^    |
   <-+  |  |    |
     |  +--L2   |
     |     ^    |
     |     |    |
     +-----L3---+
</code>```

Now imagine a feature for this project requires changes in P1 and L3 which change the interface of L3. Now add projects P2 and P3 into the mix, which also refer to these libraries. We cannot afford to switch them all to the new interface, run all the tests, and deploy the new software. So what's the alternative?

implement the new interface in L3

make a pull request for L3 and wait for the review

merge the change

create a new release of L3

start working on the feature in P1 by making it refer to L3's new release, then implement the feature on P1's feature branch

make a pull request, have this reviewed, and merged

(I just noticed that I forgot to switch L1 and L2 to the new release. And I don't even know where to stick this in, because it would need to be done in parallel with P1...)

This is a tedious, error-prone, and very long process to implement this feature, it requires to independent reviews (which makes it much harder to review), does not scale at all, and is likely to put us out of business because we get so bogged down in process we never get anything done.

But how do we employ branching and tagging in order to create a process that allows us to implement new features in new projects without too much overhead?

答:
There is a simple solution: cut release branches across whole repository, merge all fixes to all actively shipped releases (it is easy in clear-case should be possible in git).

All alternatives will create a horrible mess over time and with project growth.


问:
How can I write unit tests that simplify feature implementation?
I'm a newbie to working in software development and I read a lot about how cool unit tests are. Now, I've made my first steps into a project where I'm working with a number of equally unexperienced programmers which is why we have produced a bit of spaghetti code. I'm trying to learn how to use testing and other techniques to improve the code quality but one of my newbie co-workers says that tests make things more difficult. Apparently, he has done internships in teams where unit tests were used.

He argued that tests were constantly in his way when he tried to implement a new feature. The tests would fail after he had changed the code. So he had to adapt the tests which of course increased his workload.

But that doesn't make sense to me. I thought tests were supposed to make things easier. So, I suspect that he either didn't implement the features correctly or that the unit tests were badly done. So, I'm wondering: How can I write unit tests so that they don't fail just because a new feature was implemented?

答:
one of my newbie co-workers says that tests make things more difficult.

I think the key here is what things? There are lots of processes involved in software development. Writing executable code is only one of them.

If we focus on writing executable(/compilable/etc.) code, then writing tests does make that more difficult, simply because there's more code to look after. For example, if we make a breaking-change like renaming a function, we will have to update the test code too, in order to achieve our goal of "executable code".

Of course, having executable code isn't the end goal: for a business the end goal is usually making money; for a developer the end goal is usually reducing software's buginess or increasing its feature set/usefulness, in order to support the business's money-making plan.

Software is so complex that it's rare to fix one bug or introduce one feature in isolation. Usually the changes we make introduce new bugs, or expose/worsen existing bugs. Adding new features can break old ones, either directly (they don't do what they used to) or conceptually (they don't make sense given the new feature).

The point of testing is to try and objectively keep track of "buginess" and feature sets. By having a test suite check that existing features work, we give ourselves some confidence that our work is increasing the feature set, rather than adding new things at the expense of old. By having a test suite check inputs/paths which are important, anticipated to cause problems (edge-cases), or have previously caused problems (regression tests), we give ourselves some confidence that "buginess" is decreasing, rather than fixing new bugs at the expense of old.

Testing follows a common pattern in software engineering: testing is claimed to make software better/more "agile"/less buggy/etc., but it's not really the testing which does this. Rather, good developers make software better/more "agile"/less buggy/etc. and testing is something that good developers tend to do.

In other words, performing some ritual like unit testing for its own sake will not make your code better. Yet understanding why many people do unit testing will make you a better developer, and being a better developer will make your code better, whether it has unit tests or not.

Unfortunately, we can't git pull these skills from each other. It takes time and effort, and each person must learn these things for themselves. It sounds like your colleague was forced into ritualistic testing without building up the understanding about why particular things are done.

I would recommend playing with these ideas in some toy projects. For example, if you see some explanation like "dependency injection is needed for situations like..." I would say try to make a toy example of that situation, see what problems you encounter, try to solve them, and then try to see what dependency injection is all about. That way, you will know when something is appropriate, you'll know when it's not, and you'll be able to explain and discuss different approaches to a problem (without just reciting what other people are claiming).


问:
Dependency injection of ViewModel with unmanaged parameter
I have a PersonEditViewModel which needs two other objects, the personId and the PersonRepository. PersonRepository is obtained from a service locator:

private final int personId;
public PersonEditViewModel(int id) {
    this.personId = id;
    this.personRepository = ServiceLocator.get(PersonRepository.class);
}
```

<p>But I would like to use dependency injection (DI, IoC) to obtain <code>PersonRepository</code>, preferably via constructor:</p>

<pre class="lang-java prettyprint-override"><code>public PersonEditViewModel(PersonRepository pr) {
    this.personRepository = pr;
}
</code>```

My problem is, how can I pass the personId to the constructor in DI pattern? Do I have to make a setter for id - then DI changes the logic of the PersonEditViewModel (the personId field cannot be final)? Is it insufficiency of DI pattern that I cannot pass data objects to the constructor, or do I have to switch my mind and design my ViewModels other way, probably use other patterns to pass data objects to them?

Edit: Changed my question using personId and PersonRepository to be closer to common situations.

答:
DI containers are generally used for plugging a limited number of long-lived objects together. Think of them as building the runtime structure of your program. Person looks like an entity to me - it will be loaded, used and discarded often. Also, you could potentially have an unlimited number of Person objects and it would not make much sense to use a container to configure them.

What you probably need is a PersonFactory and/or PersonRepository for managing the lifecycle of Person objects. These can be configured using a container. You could then wrap the factory/repository with another factory/repository that "injects" the Person into the ViewModel. The other services then use this factory/repository to do their work.

Hope that helps a bit.


问:
How do you judge if you're paid enough?
How do you evaluate how much you feel you ought to be paid as a junior programmer?</p>

答: This is likely to be quite a different take as this isn't looking at compensation relative to others but rather in contrast to the rest of your life.  Do you make enough to pay your bills and live a good lifestyle?  Good being rather subjective here obviously as some people can live on a shoestring and others want to make millions each year.  Another point here is to note that there are things beyond salary in terms of compensation that should also be counted though some of these can be hard to quantify such as how good is the work environment, the quality of the work being requested and personal satisfaction in doing it.</p>

ContentLicense: CC BY-SA 2.5

Title: How do you judge if you're paid enough?


问:
WCF service with methods to fetch data
I'm planning on building a WCF service that will fetch data entities from a Sql Server database. And I'm currently struggling with best practices issues.

The thing is that there's a few different ways for a user to fetch different data. For example, customer orders can be obtained from a date range, but this date range could apply to either the date the command was processed, the deadline date or the date it's actually going to be shipped.

If client apps were directly speaking to Sql Server this would be easy enough. But now with WCF I feel I must do service changes each time I want to introduce a new way of interrogating data (new service API). This means having to take down the service, losing state, updating it and restarting it.

I could of course pass a filter string to my service methods but security wise it doesn't seem to be a good idea.

As you can probably tell by now I'm pretty green with WCF and there's probably something I'm missing. Any guidance would be much appreciated.

答:
No i think you're right. Of course you could also design your interface to be more flexible regarding querying. Let's just call it "design ahead". But of course this conflicts with YAGNI. So you'll need to compromise.

Another alternative would be to run the old and the new service version on different ports /URLs - thus getting rid of the downtime. You'll still have to switch over "old" clients to "new" clients at some point, but maybe at a more convenient time.
Of course this also entails more SW and deployment complexity which results in higher costs.

So as long as you can live with the downtimes it's probably just the way to go.

Title: WCF service with methods to fetch data


答:
In addition to what Ian has said in his answer, the following should give you a different perspective around this thing.

I try to answer following two questions about a dependency before I decide on the mechanism to pass the dependency object around.

Am I going to be using the dependency?

Who is responsible for instantiating the dependency?

The answer to first question in your context (I being PersonEditViewModel) is yes. So somehow PersonEditViewModel needs to get hold of appropriate Person instance. Note that "appropriate" is key here but lets look into that in a bit.

Coming to second question, who is responsible for instantiating Person class? Is it your IoC container? I don't think so. You are probably going to be loading appropriate instance of Person class from a database or by calling a REST/WCF service. In any case, you should have another guy in the equation which is responsible for giving you the right Person instance. If you are loading it from database then that guy can be a repository object. In which case, your next dependency is repository. Ask the same set of questions about repository again. Answer to first one is obviously yes. With regards to second one - can IoC container give an instance of (notice, there is no "appropriate" here) a repository. Yes, it can. So that becomes my dependency.

Coming to "Appropriate" - you are putting together this view model for a particular person instance. This particular person instance needs to be fetched from somewhere using right set of parameters like id, email address, name etc. You need a specialised implementation (repository for instance) to do that job. You cannot expect that IoC container would just hydrate this particular object for you somehow.

Title: Dependency injection of ViewModel with unmanaged parameter

Body:
I have a PersonEditViewModel which needs two other objects, the personId and the PersonRepository. PersonRepository is obtained from a service locator:

private final int personId;
public PersonEditViewModel(int id) {
    this.personId = id;
    this.personRepository = ServiceLocator.get(PersonRepository.class);
}
```

<p>But I would like to use dependency injection (DI, IoC) to obtain <code>PersonRepository</code>, preferably via constructor:</p>

<pre class="lang-java prettyprint-override"><code>public PersonEditViewModel(PersonRepository pr) {
    this.personRepository = pr;
}
</code>```

My problem is, how can I pass the personId to the constructor in DI pattern? Do I have to make a setter for id - then DI changes the logic of the PersonEditViewModel (the personId field cannot be final)? Is it insufficiency of DI pattern that I cannot pass data objects to the constructor, or do I have to switch my mind and design my ViewModels other way, probably use other patterns to pass data objects to them?

Edit: Changed my question using personId and PersonRepository to be closer to common situations.


问:
Migrating from SourceForge to Github, should I delete the SF repository entirely?
It's long overdue, but after a few too many horror stories I'm finally moving a long-running project of mine from SourceForge to GitHub.

Simple question: Should I delete my SourceForge project entirely?  Or would it be better to leave behind a shell with pointers to the new location?

Leaving a shell behind might be useful to the odd soul who stumbles onto an old link to SourceForge somewhere, but I now distrust SF to the extent that I'm very hesitant to leave anything behind.  However, the GIMP and now nmap hijacks above indicate that they could conceivably create a fake copy, which would be even worse — although I doubt the project is anywhere near high-profile enough to be worth their while.

答:
I would leave a pointer to the new location.

Leaving SF entirely seems not to protect you from bundling your stuff with third-party software, when I read the media reports correctly.


答:
I would commit a new revision (or several) that deletes all files except for a readme.txt containing the new link. Then I'd build a new release containing just that readme.txt (so if they do decide to create a bundled .zip, at least it will contain a link to the new location and not just an old, obsolete version. You can also, helpfully, include details of how to uninstall any crapware that might have found its way into the download from SF)

Trying to stop them creating these bundled releases is not worthwhile, but I think its not worth their while to figure out which was the last 'real' release you made.

Title: Migrating from SourceForge to Github, should I delete the SF repository entirely?

Body:
It's long overdue, but after a few too many horror stories I'm finally moving a long-running project of mine from SourceForge to GitHub.

Simple question: Should I delete my SourceForge project entirely?  Or would it be better to leave behind a shell with pointers to the new location?

Leaving a shell behind might be useful to the odd soul who stumbles onto an old link to SourceForge somewhere, but I now distrust SF to the extent that I'm very hesitant to leave anything behind.  However, the GIMP and now nmap hijacks above indicate that they could conceivably create a fake copy, which would be even worse — although I doubt the project is anywhere near high-profile enough to be worth their while.


答:
There's nothing wrong with having distinct methods in your web service.  This makes the service have a very explicit contract and it should easy to use for your clients.  For example, your initial service may have:

GetDeadlineOrders

GetProcessedOrders

If you have to add another method in the future like:

GetExpiredOrders

Your service is forward compatable so existing client will not be effected and clients who want to use the newer functionality can do so.

The easiest way to manange this is with versioning as @BatteryBackupUnit has mentioned prior.  By running different versions clients can upgrade in the future without being forced to upgrade when your service is deployed.

There is just a diffferent URL, in the past example the services could be:

http://mywcfservice/v1 (Has processed and deadline methods)

http://mywcfservice/v2 (Has process, deadline, and expired methods)

One just keeps N versions available and rolls off lower versions as needed giving clients plenty of advanced notice.

The other way is to design a more generic method:

GetOrders

This method would take in another parameter/object that would have the necessary details to formulate the query.  One way of implementating generic methods is to use a dictionary of name/value pairs in the contract so that it can be extended without changing the schema.  This makes the service less explicit and harder to use because now the client can really pass any name/value pair in the service call and it is up to the code to parse it and build the proper query to the database.

If the service is going to change frequently, it may be better to go the generic route so the contract never changes.  Bear in mind that with such a loose contract definition there could be more error requests and misunderstanding between client/service.

If there are planned releases, like every quarter, then having an defined schema with different versions will be OK and easier to use.  Just version the releases and make your service forward compatible and it should be good to go.

Title: WCF service with methods to fetch data

Body:
I'm planning on building a WCF service that will fetch data entities from a Sql Server database. And I'm currently struggling with best practices issues.

The thing is that there's a few different ways for a user to fetch different data. For example, customer orders can be obtained from a date range, but this date range could apply to either the date the command was processed, the deadline date or the date it's actually going to be shipped.

If client apps were directly speaking to Sql Server this would be easy enough. But now with WCF I feel I must do service changes each time I want to introduce a new way of interrogating data (new service API). This means having to take down the service, losing state, updating it and restarting it.

I could of course pass a filter string to my service methods but security wise it doesn't seem to be a good idea.

As you can probably tell by now I'm pretty green with WCF and there's probably something I'm missing. Any guidance would be much appreciated.


答:
Hey i am a new programmer too and i work at a company that has many many different projects, some use unit tests and some don't.  My personal expereince urges me to tell you to use them.  But don't worry, you get to choose the impact it has on your work load.

You can setup your unit tests in 2 ways (probably more).  The first way is to have your unit tests plugin to you code directly.  For example your project has a method that accepts 2 variables and outputs another.  You can create test data and have your unit test call the method.  This method is good if you want to ensure that your code is working correctly.  However if you changed that method in your code without updating the unit test then, of course your unit test will fail.

Another way of doing it that does not impact your code at all, is by by simply copying and pasting in all the code you want to test in a unit test and creating all the faux data to go along with it.  This will not alert you in anyway if your code is failing in your project, but it does give you a way to test your methods and make sure they work in the context of your unit test.

Title: How can I write unit tests that simplify feature implementation?

Body:
I'm a newbie to working in software development and I read a lot about how cool unit tests are. Now, I've made my first steps into a project where I'm working with a number of equally unexperienced programmers which is why we have produced a bit of spaghetti code. I'm trying to learn how to use testing and other techniques to improve the code quality but one of my newbie co-workers says that tests make things more difficult. Apparently, he has done internships in teams where unit tests were used.

He argued that tests were constantly in his way when he tried to implement a new feature. The tests would fail after he had changed the code. So he had to adapt the tests which of course increased his workload.

But that doesn't make sense to me. I thought tests were supposed to make things easier. So, I suspect that he either didn't implement the features correctly or that the unit tests were badly done. So, I'm wondering: How can I write unit tests so that they don't fail just because a new feature was implemented?


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
When key developers leave and management doesn't care

When key developers leave and none of the other developers care

Number one is usually indicative of managers who are severely out-of-touch with the team dynamics (who is the "10x super star", who are the decent programmers, and how they interact with each other etc).

Number two usually indicates severe lack-of-interest on the part of the remaining developers.


问:
DTO and JPA Version
I have DB tables representing Employees and Departments. The server side(JavaEE) contains JPA entities representing the same.

The client is a standalone client and communicates with the server using DTOs. In my case, a single DTO contains both the Employee and Dept details.

I want to implement Optimistic locking using the Version annotation on these entities, but there is an issue: When the client send the DTO with the updated values to the server method(webservice), the server method creates entities using the values in the DTO and then it finds the entity using the find() method on JPA and then calls update(). There is not much gap between find() and update().

But the issue is that the value coming from the DTO itself might be stale. Since I am using standalone client, I do not have the context of the server's JPA entities. JPA itself cannot find that the value is old (because the version between find() and update() matches) and overwrites the entity with stale data. Is there a way to solve this issue?

答:
Optimistic locking using version numbers is based on the principle that you know which version of the data was retrieved from the database before making any modifications, so that you can verify that no intermediate updates have taken place between your retrieval of an entity and writing your changes back.

For this to work, the version number must be an integral part of the entity (and must only be changed by the database). This means that the version number must also be communicated in your DTO to the client, preferably as a read-only attribute.

If the version number is part of the DTO, then you can detect stale data in two ways:

The find method checks the version number against the current version of the entity and reports "entity version mismatch" when the two don't match.

The update method fails if the version of the entity doesn't match the version number in the database. To avoid race conditions, this check should always be performed, even if the find function also checks the version number.

If you did detect stale data, you can react in several ways:

Report an error and let the user refresh the entity and re-enter his changes

Report the conflict to the user and let him merge his changes into the new version of the entity (showing what was changed externally and what was changed by the user).

Try to perform an automated merge, and if that doesn't work fall back to 2 (for example if multiple edits were made to the same field).

Title: DTO and JPA Version


问:
Relation between Kernel & BIOS routines
How does a Kernel provides different functionality to OS? Does it use the BIOS routines or use special device drivers for this, or something else? If uses BIOS how does it come to know which routine performs what because different BIOS vendors have different coding? If not then what's the use for BIOS routines?</p>

答:
How does a Kernel provides different functionality to OS?

The OS would access kernel functionality via a system call interface.

In the x86 architecture the int instruction takes an interrupt number as an argument which it uses to generate a software interrupt to which an interrupt handler will respond to. The kernel would have its own interrupt number. The kernel knows what to do because there is a calling convention to follow when attempting to utilize a system call.

As an example, to open a file on an x86 Linux machine, one would place the integer 5 in the eax register (the system call number), a pointer to the filename string in register ebx, flags in register ecx, mode in register edx and then call the software interrupt with int $0x80. The kernel then services the system call and returns control back to the program. There are more efficient ways to access kernel services but they are OS specific.

Does it use the BIOS routines or use special device drivers for this, or something else?

Modern kernels would interface with hardware via device drivers.

how does it come to know which routine performs what because different BIOS vendors have different coding?

You interface with the BIOS via interrupts as well, except they would need to take place in "real" mode as opposed to the "protected" mode which CPUs typically operate in. Real mode is a 16 bit mode which gives software unlimited access to all addressable physical memory and peripherals. These are not BIOS specific but CPU architecture specific.

If not then what's the use for BIOS routines?

To be used during the initial boot process mainly.

Title: Relation between Kernel & BIOS routines


答:
In addition to FX Cop / VS's Code Analysis (they are the same thing, one is command line, one is in the IDE) as mentioned by others, NDepend can help. It will allow you to run queries to determine all callers and callees, right on up the chain. Think of it as letting you run reports on your code. It's not the be-all and end-all, but helps you to get several steps closer to where you want to be at the least.

The fundamental problem in turning to code analysis here is that public members are hard to conclusively say "not used" for a tool. I'm not familiar with a code analysis kit that has rules that say "This bunch of assemblies represent the whole ecosystem so if a method isn't called anywhere, let me know." I guess that once you get into derived types, that gets messy for an automated static code analysis engine.

Title: Code cleanup methods and/or code coverage tools

Body:
I have an application at work, which I started work on about 7 years ago. This was my first engagement in ASP.NET web applications, and coming from a Win32 background I had a hard time adjusting.

All this time, both the project and myself have "matured" and now most parts of it are well defined, properly structured and readable. However, there is a significant piece of it, that is "old junk". By that I mean old obsolete code, that was not working well, or was not properly structured, which has been replaced, but left in the source files instead of being removed. I must note here, that I was not the sole developer, but did most of the coding throughout.

What I want to do, is whenever I have free time at work, to remove the old obsolete and unused code. Are there any techniques/methodologies that I can use/follow in order to do this more efficiently? Any tools perhaps?

EDIT: (clarification based on feedback)
The code I am talking about is not used anywhere, and is not called from anywhere in the project. What I need is way to find out where the code resides, since we are talking about a large codebase. So something in terms of code coverage tools would help. Any suggestions for asp.net projects? (the particular case is in Web Site project form)


问:
Member and Function Injection in C++ Across Multiple Classes
I have a problem in which a variety of classes in C++ will want some functionality that is neither a "has a" nor an "is a" relationship.
The problem is that there are some members with associated functions having to do with handling player pointers that some menus and in game objects will need to have.
I could copy the functionality across all of them, but I'd rather inject the functionality as advice, so that the functionality is shared.
The classes that need the functionality do not share a super in the class tree.

Normally I might use something akin to aspect orientation, making an Aspect that has all the desired functionality and adding it to all of the classes as advice, but because of the C++ codebase at the company I cannot do this.

Is there a good "plain C++" solution to this that I'm overlooking? (c++11 allowed)
Right now I hope to use interfaces to do something similar.

edit:
i'll be experimenting with each solution, perhaps asking further questions, and will figure out the best solution within the next few days.
want to give this thorough consideration for future use.

答: You can try using std::function to pass function pointers around, or just raw function pointers if not (I have used the latter for lookup tables of routines to call based on some data input)</p>


答:
Is all the functionality known at compile time?  If so,
template metaprogramming might work.  See a real example here, but
something like this ---

```<code>template<class T> ExtraFunctionality {
  //do something with instances of class T
}

template<class T> OtherExtraFunctionality {
  //do something else with instances of class T
}

template< template<class> class Extras = ExtraFunctionality >
class Menu: public AbstractMenu, Extras<Menu> {
  typedef Extras<Menu> Ext;  //for convenience - not required
  //do something with what you inherited from Extras.
}

template< template<class> class Extras = ExtraFunctionality >
class GameObject: public AbstractGameObject, Extras<GameObject> {
  //same deal
}
</code>```

now you can instantiate

```<code>Menu<> menu;
</code>```

for the Menu with ExtraFunctionality or

```<code>Menu<OtherExtraFunctionality>
</code>```

if you want something different.

This is an example of CRTP mentioned by @Deduplicator.

Title: Member and Function Injection in C++ Across Multiple Classes

Body:
I have a problem in which a variety of classes in C++ will want some functionality that is neither a "has a" nor an "is a" relationship.
The problem is that there are some members with associated functions having to do with handling player pointers that some menus and in game objects will need to have.
I could copy the functionality across all of them, but I'd rather inject the functionality as advice, so that the functionality is shared.
The classes that need the functionality do not share a super in the class tree.

Normally I might use something akin to aspect orientation, making an Aspect that has all the desired functionality and adding it to all of the classes as advice, but because of the C++ codebase at the company I cannot do this.

Is there a good "plain C++" solution to this that I'm overlooking? (c++11 allowed)
Right now I hope to use interfaces to do something similar.

edit:
i'll be experimenting with each solution, perhaps asking further questions, and will figure out the best solution within the next few days.
want to give this thorough consideration for future use.

Body:
Is all the functionality known at compile time?  If so,
template metaprogramming might work.  See a real example here, but
something like this ---

template<class T> ExtraFunctionality {
  //do something with instances of class T
}

template<class T> OtherExtraFunctionality {
  //do something else with instances of class T
}

template< template<class> class Extras = ExtraFunctionality >
class Menu: public AbstractMenu, Extras<Menu> {
  typedef Extras<Menu> Ext;  //for convenience - not required
  //do something with what you inherited from Extras.
}

template< template<class> class Extras = ExtraFunctionality >
class GameObject: public AbstractGameObject, Extras<GameObject> {
  //same deal
}

now you can instantiate

Menu<> menu;

for the Menu with ExtraFunctionality or

Menu<OtherExtraFunctionality>

if you want something different.

This is an example of CRTP mentioned by @Deduplicator.


问:
Instantiating a set of Objects from information in File
Let’s say I have four classes A,B,C,D.

Each of those classes contains a Tree object. This tree object needs to be built according to information stored in files f_A, f_B, f_C, f_D, for classes  A,B,C,D respectively.

So the tree in class A needs to be built according to f_A.

Now I think it is not a good idea for the Tree class doing file I/O.

One option would be that the Tree has a function buildFromString(String s) which takes the content of a file as a string and builds itself.

But again, I don’t think the Tree should do any String processing.

An alternative would be that for each class A,B,C,D we have a Tree builder Class, which takes a Tree object as a parameter, reads the corresponding file and builds the Tree.

Maybe a Factory pattern would help, but I don't see how to make use of it in this context.

But this introduces a lot of new classes.

What would be a clean way of building the trees from the files subject to which class they are instantiated from?

答:
The question how "clean" it is to have a generic builder/deserializer/factory that can create objects of different classes from textual descriptions depends on how easy this is to do in the language. In JavaScript it is trivial, since the JavaScript Object Notation is built into the language. In Java it is possible but a bit harder, since you have to muck around with reflection and explicit classloading. In something like Ada (I think, correct me if I'm wrong) it is hard to impossible.

Therefore, whether it is better to go for the meta-approach or create a parallel hierarchy of builder classes depends on how efficient, readable, maintainable etc. these alternatives are on the platform you will be using. It is almost certainly not ideal to have to create two classes for each concept in your model unless you can automate the process, but depending on circumstances, it might be the lesser of two evils.


问:
OO Design: Algorithm changing State (Information Flow Question)
I have a class Context, which contains an instance of an abstract class State, which has multiple concrete subclasses (this is an implementation of the State Pattern).

Each State subclass executes a number of algorithms, which are themselves classes, and according to the outcome of an algorithm the state in the Context class might change.

My question is how should the algorithm make this state change in the Context class?

1) A simple solution would be to pass the Context object to the algorithm, but I don’t like that the algorithm know anything about the current State / Context.

2) I could write algorithm-specific wrapper classes of the Context class, where each wrapper has only one public function, namely to set the state of the Context according to the algorithm outcome.

3) Pass a function of Context which does a specific State change as function pointer to the algorithm and execute it when the state of Context should be changed.

While 1) is in my opinion the least favorable option, 2) would introduce a lot of new classes and I am not sure to what extent 3) is doable (in C++) and how Object Oriented this is.

What is the textbook way of dealing with this situation?

答:
If the logic for choosing the next state is a part of the Algorithm classes, then clearly they must be able to communicate the specific state to change to to the Context class.

If the concept of states to change to is useless without the 'context' object (hard to tell), passing a reference to the context object should be fine - the algorithms and the context depend on each other and theres nothing you can do about it, so better make it as explicit as possible.

If algorithms dont really care if the state changes happen or not or what state is transitioned to (e.g. the logic for this resides entirely in the particular State subclass), you could pass a functor to the algorithm to be executed at the correct time, and the State subclass then implements the desired behavior (switching to a specific state).
You can do this using either an std::function, or if possible, by passing a lambda as a template parameter to a method of the algorithm class (which should be more performant since it can be inlined - std::function may even do a heap allocation).

So in a State subclass you might have something like:

```<code>void State::ExecuteAlgorithms(Context& context)
{
    algorithm.Execute([&context](){context.switchToState(*something*)});
}
</code>```

Where algorithm.Execute looks like:

```<code>template<typename CallbackT>
void Algorithm::Execute(CallbackT switchStateCallback)
{
    *code*
    switchStateCallback();
}
</code>```

Of course you might want to add more than one callback, or pass parameters to the callback, to allow for more complex logic for choosing the next state.

You can replace the lambda with a class (which is how its implemented internally anyways) if you dont have them available, or use std::function instead of a template if the algorithm isn't just a single method or if you dont want templates.

Body:
If the logic for choosing the next state is a part of the Algorithm classes, then clearly they must be able to communicate the specific state to change to to the Context class.

If the concept of states to change to is useless without the 'context' object (hard to tell), passing a reference to the context object should be fine - the algorithms and the context depend on each other and theres nothing you can do about it, so better make it as explicit as possible.

If algorithms dont really care if the state changes happen or not or what state is transitioned to (e.g. the logic for this resides entirely in the particular State subclass), you could pass a functor to the algorithm to be executed at the correct time, and the State subclass then implements the desired behavior (switching to a specific state).
You can do this using either an std::function, or if possible, by passing a lambda as a template parameter to a method of the algorithm class (which should be more performant since it can be inlined - std::function may even do a heap allocation).

So in a State subclass you might have something like:

void State::ExecuteAlgorithms(Context& context)
{
    algorithm.Execute([&context](){context.switchToState(*something*)});
}

Where algorithm.Execute looks like:

template<typename CallbackT>
void Algorithm::Execute(CallbackT switchStateCallback)
{
    *code*
    switchStateCallback();
}

Of course you might want to add more than one callback, or pass parameters to the callback, to allow for more complex logic for choosing the next state.

You can replace the lambda with a class (which is how its implemented internally anyways) if you dont have them available, or use std::function instead of a template if the algorithm isn't just a single method or if you dont want templates.


问:
Use StringLike instead of String in Scala?
Scala has the StringLike trait. Let's say I want to create a case class Name and internally it should save the name with some characters. Should I use case class Name(name: StringLike) or case class Name(name: String)?

The former is obviously more abstract. It means someone can give me CustomString that extends StringLike and he might overwrite some methods.

If I want to be sure the given argument behaves like the String class I know, I should use String and else StringLike. Is that correct? Are there cases in which it would make a practically difference?

Also, are there things I can do with the more specialized String that I can't do with a StringLike?

答:
Although it's usually good practice to accept as abstract of arguments as possible, in Scala you generally want to avoid directly using any types with [Repr] parameters.  They are mostly there for the convenience of the standard library implementors.

That's especially true for StringLike, which is primarily intended to augment a Java String to be able to also act like a collection of characters.  You're not  supposed to look at the man behind the curtain to see how that's accomplished.  Nor is it expected that anyone would ever make a custom StringLike implementation.

String is also much better from a simple readability standpoint.  If you need something that behaves like a String, just use a String.  In the extremely remote chance you ever need something kind of like a String, but not really, you can make the change then, and there may be a better solution.


答:
the whole tree building functionality would go into a superclass, the respective classes would basically just contain the correct filename for the tree to be built from

I don't think creating subclasses just to hardcode some values is a good idea.
A,B,C and D are basically speaking just values of the same type.

In a sense, you are looking a for a way to define specific values of the single type that is the super class (with all the file and tree handling). Like an object literal.

Depending on the language you are using, you could do this with static methods, that basically call the constructor with a hardcoded value

some pseudo code

```<code>TreeThing (String filepath) // constructor
{
    // do the tree stuff, dependign on the file
}

static TreeThing A ()
{
    return new TreeThing("fileA");
}
</code>```

Title: Instantiating a set of Objects from information in File

Body:
Let’s say I have four classes A,B,C,D.

Each of those classes contains a Tree object. This tree object needs to be built according to information stored in files f_A, f_B, f_C, f_D, for classes  A,B,C,D respectively.

So the tree in class A needs to be built according to f_A.

Now I think it is not a good idea for the Tree class doing file I/O.

One option would be that the Tree has a function buildFromString(String s) which takes the content of a file as a string and builds itself.

But again, I don’t think the Tree should do any String processing.

An alternative would be that for each class A,B,C,D we have a Tree builder Class, which takes a Tree object as a parameter, reads the corresponding file and builds the Tree.

Maybe a Factory pattern would help, but I don't see how to make use of it in this context.

But this introduces a lot of new classes.

What would be a clean way of building the trees from the files subject to which class they are instantiated from?

Body:
the whole tree building functionality would go into a superclass, the respective classes would basically just contain the correct filename for the tree to be built from

I don't think creating subclasses just to hardcode some values is a good idea.
A,B,C and D are basically speaking just values of the same type.

In a sense, you are looking a for a way to define specific values of the single type that is the super class (with all the file and tree handling). Like an object literal.

Depending on the language you are using, you could do this with static methods, that basically call the constructor with a hardcoded value

some pseudo code

TreeThing (String filepath) // constructor
{
    // do the tree stuff, dependign on the file
}

static TreeThing A ()
{
    return new TreeThing("fileA");
}


答:
Two important questions:

Do you feel good about the amount they pay you? Does it justify the responsibility?

Are you happy at work? Do they treat you well, and do you feel at home?

Compare scales all you want, these are the things that matter in the end. At other jobs you will be given other responsibilities, so you cannot really compare the other peoples salaries.

You should be payed enough so you won't have to worry about getting paid.

For me personally, it weighs both ways, when its boring at work I start looking at my salary, when its fun at work, I usually don't care how much I make because I have fun.

P.S. Extra interesting movie: http://www.youtube.com/watch?v=u6XAPnuFjJc

Title: How do you judge if you're paid enough?

Body: How do you evaluate how much you feel you ought to be paid as a junior programmer?</p>


问:
Correct approach for creating api contract
I need help regarding below:

I am trying to design an API. For creating contracts below are the two approaches:

Approach 1:

```<code>public class MyController
{
  public void MyAction1(Dictionary<string, dynamic> input)
  {
    //Use input like below
    //Read from input dictionary and apply minimal business logic if needed
    //And Call CustomDataProvider library with input object itself(DataProvider designed in such a way that it takes Dictionary and used values as procedure input. Dictionary key is same as procedure arguments.)
  }

public void MyAction2(Dictionary<string, dynamic> input)
  {
    //Use input like below
    //Read from input dictionary and apply minimal business logic if needed
    //And Call CustomDataProvider library with input object itself(DataProvider designed in such a way that it takes Dictionary and used values as procedure input. Dictionary key is same as procedure arguments.)
  }
}
</code>```

In this case we don't need data contract at all.

Approach 2:

```<code>public class MyController
{
  public void MyAction1(MyContractBusinessObject1 input)
  {
    //Do normal business logic processing using input object and call DBProvider by creating a dictionary from business object
  }

public void MyAction2(MyContractBusinessObject2 input)
  {
    //Do normal business logic processing using input object and call DBProvider by creating a dictionary from business object
  }
}
</code>```

In this case we'll have different business classes as contract for different action inputs.
Can you please suggest which of the above approaches is better and why?

Let me give an example.
Suppose My actions are doing login and new account creation. In first case input will be

```<code>new Dictionary<string, dynamic>{{"Name","myname"},{"Passowrd",'mypassword'}}
</code>```

and

```<code>new Dictionary<string, dynamic>{{"Name","myname"},{"Passowrd",'mypassword'},{"Age",myage},{"otherInfo",myotherinfo}}
</code>```

but in approach 2 input will be

```<code> class Login{
    public string Name{get; set;}
    public string Password{get; set;}
}
</code>```

and

```<code>class NewAccount{
public string Name{get; set;}
public string Password{get; set;}
public int Age{get; set;}
public OtherInfo OtherInfo{get; set;}
}
</code>```

答:
I'm going to go ahead an assume a few things here:

You're looking for a pattern to apply to multiple controllers

You have situations where a single action call can have varying amounts of data submitted (Name/Password guaranteed but sometimes age and other info are included).

If my assumptions are correct then I would suggest something to the following.

```<code>public class Contact
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

public class SpecialContact : Contact
{
    public String Title { get; set; }
}

public class AnotherSpecialContact : Contact
{
    public String Phone { get; set; }
}

public class ContactController
{
    public void MyAction(Contact contact)
    {
        // VALIDATE: Example validation provided.
        if (String.IsNullOrWhiteSpace(contact.FirstName)) { return; }
        if (String.IsNullOrWhiteSpace(contact.LastName)) { return; }

        if (contact is SpecialContact)
        {
            SpecialContact specialContact = contact as SpecialContact;
            // Do things SpecialContact specific.
        }
        else if (contact is AnotherSpecialContact)
        {
            AnotherSpecialContact anotherSpecialContact = contact as AnotherSpecialContact;
            // Do things AnotherSpecialContact specific.
        }

        // Do things Contact specific.
    }
}
</code>```

Reasons for my suggestion:

You, as the API developer, know that the data you require is there and can do simple validation to make sure. If it was a dictionary or dynamic type then you'd have to do the type validation on top of regular validation.

As you can see from the SpecialContact and AnotherSpecialContact examples you can extend the action to handle special conditions where extra data is present. If you have situations where less data is present then that means you have the wrong base-class (i.e. Contact in this scenario).

(Sort of a repeat of #1 but...) You're using a statically typed language so why go against that with dynamic? The only time I've found dynamic particularly helpful is in cases of Reflection, any other time I've found it is the same or more work as the alternatives. If you think you need dynamic, give Object a try first.

Body:
I'm going to go ahead an assume a few things here:

You're looking for a pattern to apply to multiple controllers

You have situations where a single action call can have varying amounts of data submitted (Name/Password guaranteed but sometimes age and other info are included).

If my assumptions are correct then I would suggest something to the following.

public class Contact
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

public class SpecialContact : Contact
{
    public String Title { get; set; }
}

public class AnotherSpecialContact : Contact
{
    public String Phone { get; set; }
}

public class ContactController
{
    public void MyAction(Contact contact)
    {
        // VALIDATE: Example validation provided.
        if (String.IsNullOrWhiteSpace(contact.FirstName)) { return; }
        if (String.IsNullOrWhiteSpace(contact.LastName)) { return; }

        if (contact is SpecialContact)
        {
            SpecialContact specialContact = contact as SpecialContact;
            // Do things SpecialContact specific.
        }
        else if (contact is AnotherSpecialContact)
        {
            AnotherSpecialContact anotherSpecialContact = contact as AnotherSpecialContact;
            // Do things AnotherSpecialContact specific.
        }

        // Do things Contact specific.
    }
}

Reasons for my suggestion:

You, as the API developer, know that the data you require is there and can do simple validation to make sure. If it was a dictionary or dynamic type then you'd have to do the type validation on top of regular validation.

As you can see from the SpecialContact and AnotherSpecialContact examples you can extend the action to handle special conditions where extra data is present. If you have situations where less data is present then that means you have the wrong base-class (i.e. Contact in this scenario).

(Sort of a repeat of #1 but...) You're using a statically typed language so why go against that with dynamic? The only time I've found dynamic particularly helpful is in cases of Reflection, any other time I've found it is the same or more work as the alternatives. If you think you need dynamic, give Object a try first.


问:
Handling Code Signing in a Source Controlled Environment
Just a quick question, hopefully:

My team maintains a piece of software that uses ClickOnce deployment and is signed with a certificate. We keep the public certificate that is actually used on a separate machine that is only used for signing. That works fine.

Where we occasionally run into issues, though, is when someone has to sign it locally with a new test certificate so they can build and test the solution. Inevitably, this new certificate fingerprint gets pushed up to version control as part of the project settings file. It doesn't cause an issue on the signing box as its own certificate settings are never pushed to the Git server, so pulls from that machine don't override the local changes. However, it does cause issues for everyone else as they have their own test certificate that gets used on their local machine.

Is there a correct way to handle this situation? Maybe some way in Git to exclude changes from just a particular part of a configuration file, rather than the entire thing?

答:
There's no way in Git to exclude changes to just part of a file. What you can usually do however is externalise that part of the file to a different config file and then add that other config file to the .gitignore file. That lets each developer customise the config as they require but stops them accidentally checking in their changes and affecting others.

How you do this obviously varies depending on language/framework. As you mention ClickOnce I'm going to assume it's a .Net solution in this case. Let's say you've got a web.config with the following content

```<code><signingInfo>
  <certificate path="C:\test\whatever.cert">
</signingInfo>
</code>```

You can replace this with

```<code><signingInfo configSource="signing.config">
</code>```

"signing.config" is added to the .gitignore file. Each developer then sets up signing.config as they need locally and there's no need to explicitly remember not to commit changes to it.

Body:
There's no way in Git to exclude changes to just part of a file. What you can usually do however is externalise that part of the file to a different config file and then add that other config file to the .gitignore file. That lets each developer customise the config as they require but stops them accidentally checking in their changes and affecting others.

How you do this obviously varies depending on language/framework. As you mention ClickOnce I'm going to assume it's a .Net solution in this case. Let's say you've got a web.config with the following content

<signingInfo>
  <certificate path="C:\test\whatever.cert">
</signingInfo>

You can replace this with

<signingInfo configSource="signing.config">

"signing.config" is added to the .gitignore file. Each developer then sets up signing.config as they need locally and there's no need to explicitly remember not to commit changes to it.


答:
If not then what's the use for BIOS routines?

To get a kernel running properly you need to load it (and possibly other things - drivers, "init RAM disk", etc) from somewhere (disk, CD, network) into memory. The kernel will also need various pieces of information (e.g. a physical memory map) and may want some pieces of hardware configured a certain way (e.g. video card might be configured early during boot so OS can use video as a generic "frame buffer" when there is no video driver). The BIOS is used for all of these things before the OS is able to do anything itself.

Basically, the BIOS (or something that provides similar functionality - e.g. UEFI) is required very early during boot and then typically discarded after that.

Also note that BIOS functions and UEFI functions are designed for "single CPU, single tasking, (effectively) no paging, synchronous interface"; and most modern OSs are designed for "multi CPU, multi-tasking, with paging, asynchronous interface". This makes the device drivers built into firmware (both BIOS and UEFI) useless for a modern OS after boot.

Title: Relation between Kernel & BIOS routines

Body: How does a Kernel provides different functionality to OS? Does it use the BIOS routines or use special device drivers for this, or something else? If uses BIOS how does it come to know which routine performs what because different BIOS vendors have different coding? If not then what's the use for BIOS routines?</p>


问:
Expandable alternative to Visitor pattern for tree traversal?
I have a tree containing various subtypes of the my base node class. I now want to traverse this tree and do something with the nodes depending on their type.

The most straightforward idea is to just define a method doSomething in my base node class, but this means that to add functionality I have to add a method to all existing node subtypes.

The first thing that comes to mind to solve this is the Visitor pattern. However, I want to be able to create new subtypes without having to change all existing visitors - I want the new subtypes to inherit the way they are handled from their base type.

I think using dynamic_cast should do the trick, but I understood that it is a costly operation, and it will be called a lot, so that is not a good solution. And many people say it is a sign of bad design, although I do not see the problem in this case.

At this moment I am using the first solution as I see foresee much more added types than functionality, but is there a better way to do this?

答:
I want the new subtypes to inherit the way they are handled from their base type

The classic GOF visitor pattern behaves exactly like that. For example, look the Wikipedia CarElement example (it is a Java example, but the important part is similar in C++). Lets assume you add new Wheel types like SquareWheel, RoundWheel by inheriting them from Wheel. Then, visit(Wheel &wheel) will process SquareWheel as well as RoundWheel, as long as you do not define any methods visit(SquareWheel &wheel) or visit(RoundWheel &wheel).


问:
Api for CMS And Mobile applications either separate or same
I would like to ask an architect based question

What  is more secure and most standard way to follow.For let's say a mobile application,

Should the Api for mobile interaction with server be different than CMS (cms to use its own database queries AND functions) or should cms and app use same api integrated inside CMS.

答:
I'm going to assume some things about this question.

When you say API, you mean an API based on a Web Service (HTTP/SOAP/Etc).

When you say CMS, you are referring to a CMS for a website, and that it has it's own API.

The nice thing about having an API, is that it can give you can get and send data (JSON/XML/Etc) from the service in a language agnostic way. Any system in which you can view webpages, means that it has the capability of consuming an HTTP API, which is nearly any language or framework.

This means that your android/ios/web app basically only have two concerns, UX and communication with your web service. Making sure that your service is doing the heavy lifting means that your interface projects can be generally "dumb". This way helps prevent duplicated code between all projects (DRY).

I'm willing to doubt that the API included in the CMS is going to cover all of your needs, so I would recommend implementing your own as well for logic specific to your business logic.

This is only highlighting the benefit of why you may want to do this approach. Weather or not these techniques seem useful for your specific project is up to you.


问:
How to transfer contexts among separate node.js environments?
Lets suppose I have my app running on machine A, at some point I need to shut down that machine, and transfer my app to machine B to continue its process. so I need to be able to save and restore context of my app.

How can implement that?

To be more specific, my question is: How can I save/restore application context in node.js?

答:
There are two ways to do this:

Send a "shutdown" message to your app on Machine A; refuse new clients, wait for existing requests to wind down, close the app, and spin it up on machine B, or

Send a "freeze" message to your app on Machine A; refuse new clients, suspend all activities, serialize the state of all activities to disk, close the app, restart the app on machine b.  Send an "unfreeze" message to your new app instance, which will re-hydrate the existing activities and resume them.

Option 1 is by far the simplest and most reliable choice, as it only requires you to stop accepting requests and detect when there are no more tasks to process.


答:
I recommend you this website: OSDev Wiki

It is a very fine page that gives you great introductions to the very basics of an operating system as well as a lot of example codes to even write your own OS.

It might be a little-low level but besides the very detailed descriptions there are also some general explanations on this topic. Imho it is a great source if one really wants to understand Operating Systems.

Try this:

What is a kernel?

The kernel of an operating system is something you will never see. It
  basically enables any other programs to execute. It handles events
  generated by hardware (called interrupts) and software (called system
  calls), and manages access to resources.

The hardware event handlers (interrupt handlers) will for instance get
  the number of the key you just pressed, and convert it to the
  corresponding character stored in a buffer so some program can
  retrieve it.

The system calls are initiated by user-level programs, for opening
  files, starting other programs, etc. Each system call handler will
  have to check whether the arguments passed are valid, then perform the
  internal operation to complete the request.

Most user programs do not directly issue system calls (except for ASM
  programs, for instance), but instead use a standard library which does
  the ugly job of formatting arguments as required by the kernel and
  generating the system call. (For example, the C function fopen()
  eventually calls a kernel function that actually opens the file.)

The kernel usually defines a few abstractions like files, processes,
  sockets, directories, etc. which correspond to an internal state it
  remembers about last operations, so that a program may issue a session
  of operation more efficiently.

And maybe in addition read this.

BIOS

BIOS (Basic Input/Output System) was created to offer generalized
  low-level services to early PC system programmers. The basic aims
  were: to hide (as much as possible) variations in PC models and
  hardware from the OS and applications, and to make OS and application
  development easier (because the BIOS services handled most of the
  hardware level interface).

  ...

Title: Relation between Kernel & BIOS routines


问:
Is it good practice to implement two Java 8 default methods in terms of each other?
I'm designing an interface with two related methods, similar to this:

```<code>public interface ThingComputer {
    default Thing computeFirstThing() {
        return computeAllThings().get(0);
    }

    default List<Thing> computeAllThings() {
        return ImmutableList.of(computeFirstThing());
    }
}
</code>```

Around half the implementations will only ever compute one thing, while the other half may compute more.

Does this have any precedent in widely-used Java 8 code?  I know Haskell does similar things in some typeclasses (Eq for example).

The upside is I have to write significantly less code than if I had two abstract classes (SingleThingComputer and MultipleThingComputer).

The downside is that an empty implementation compiles but blows up at runtime with a StackOverflowError.  It's possible to detect the mutual recursion with a ThreadLocal and give a nicer error, but that adds overhead to non-buggy code.

答:
TL;DR: do not do this.

What you show here is brittle code.

An interface is a contract. It says "regardless of what object you get, it can do X and Y." As it is written, your interface does neither X nor Y because it is guaranteed to cause a stack overflow.

Throwing an Error or subclass indicates a severe error that should not be caught:

An Error is a subclass of Throwable that indicates serious problems
that a reasonable application should not try to catch.

Furthermore, VirtualMachineError, the parent class of StackOverflowError, says this:

Thrown to indicate that the Java Virtual Machine is broken or has run
out of resources necessary for it to continue operating.

Your program should not be concerned with JVM resources. That is the job of the JVM. Making a program that causes a JVM error as a part of normal operation is bad. It either guarantees your program will crash, or compels users of this interface to trap errors it should not be concerned with.

You might know Eric Lippert from such endeavors as emeritus "member of the C# language design committee." He talks about language features pushing people toward success or failure: while this is not a language feature or part of language design, his point is equally as valid when it comes to implementing interfaces or using objects.

You remember in The Princess Bride when Westley wakes up and finds
himself locked in The Pit Of Despair with a hoarse albino and the
sinister six-fingered man, Count Rugen? The principle idea of a pit of
despair is twofold. First, that it is a pit, and therefore easy to
fall into but difficult work to climb out of. And second, that it
induces despair. Hence the name.

Source: C++ and the Pit Of Despair

Having an interface throw a StackOverflowError by default pushes developers into the Pit of Despair and is bad idea. Instead, push developers toward the Pit of Success. Make it easy to use your interface correctly and without crashing the JVM.

Delegating between the methods is fine here. However, the dependency should go one way. I like to think of method delegation like a directed graph. Each method is a node on the graph. Each time a method calls another method, draw an edge from the calling method to the method called.

If you draw a graph and notice it is cyclic, that is a code smell. That is a potential for pushing developers in the Pit of Despair. Note that it should not be categorically forbidden, only that one must use caution. Recursive algorithms specifically will have cycles in the call graph: that is fine. Document it and warn developers. If it is not recursive, try to break that cycle. If you cannot, find out what inputs might cause a stack overflow and either mitigate them or document it as a last case if nothing else will work.

ContentLicense: CC BY-SA 4.0


问:
Should I prefer composition or inheritance in this scenario?
Consider an interface:

```<code>interface IWaveGenerator
{
    SoundWave GenerateWave(double frequency, double lengthInSeconds);
}
</code>```

This interface is implemented by a number of classes which generate waves of different shapes (for example, SineWaveGenerator and SquareWaveGenerator).

I want to implement a class that generates a SoundWave based on musical data, not raw sound data. It would receive the name of a note and a length in terms of beats (not seconds), and internally use the IWaveGenerator functionality to create a SoundWave accordingly.

Question is, should the NoteGenerator contain an IWaveGenerator or should it inherit from an IWaveGenerator implementation?

I'm leaning towards composition because of two reasons:

1- It allows me to inject any IWaveGenerator to the NoteGenerator dynamically. Also, I only need one NoteGenerator class, instead of SineNoteGenerator, SquareNoteGenerator, etc.

2- There's no need for NoteGenerator to expose the lower-level interface defined by IWaveGenerator.

However I'm posting this question to hear other opinions regarding this, maybe points I haven't thought of.

BTW: I would say NoteGenerator is conceptually an IWaveGenerator because it generates SoundWaves.

答:
2- There's no need for NoteGenerator to expose the lower-level
  interface defined by IWaveGenerator.

Sounds like NoteGenerator is not a WaveGenerator, so therefore should not implement the interface.

Composition is the correct choice.


答:
It is fine for NoteGenerator to implement the interface, and also, for NoteGenerator to have an internal implementation that references (by composition) another IWaveGenerator.

Generally, composition results in more maintainable (i.e. readable) code, because you don't have complexities of overrides to reason over.  Your observation about the matrix of classes you'd have when using inheritance is also on point, and can probably be thought of as a code smell pointing toward composition.

Inheritance is better used when you have an implementation that you want to specialize or customize, which doesn't seem to be the case here: you just need to use the interface.

Title: Should I prefer composition or inheritance in this scenario?

Body:
Consider an interface:

```<code>interface IWaveGenerator
{
    SoundWave GenerateWave(double frequency, double lengthInSeconds);
}
</code>```

This interface is implemented by a number of classes which generate waves of different shapes (for example, SineWaveGenerator and SquareWaveGenerator).

I want to implement a class that generates a SoundWave based on musical data, not raw sound data. It would receive the name of a note and a length in terms of beats (not seconds), and internally use the IWaveGenerator functionality to create a SoundWave accordingly.

Question is, should the NoteGenerator contain an IWaveGenerator or should it inherit from an IWaveGenerator implementation?

I'm leaning towards composition because of two reasons:

1- It allows me to inject any IWaveGenerator to the NoteGenerator dynamically. Also, I only need one NoteGenerator class, instead of SineNoteGenerator, SquareNoteGenerator, etc.

2- There's no need for NoteGenerator to expose the lower-level interface defined by IWaveGenerator.

However I'm posting this question to hear other opinions regarding this, maybe points I haven't thought of.

BTW: I would say NoteGenerator is conceptually an IWaveGenerator because it generates SoundWaves.


答:
Whether or not NoteGenerator is "conceptually" an IWaveGenerator does not matter.

You should only inherit from an interface if you plan on implementing that exact interface according to the Liskov Substitution Principle, i.e. with the correct semantics as well as the correct syntax.

It sounds like your NoteGenerator might have syntactically the same interface, but its semantics (in this case, the meanings of the parameters it takes) will be very different, so using inheritance in this case would be highly misleading and potentially error-prone. You're right to prefer composition here.


问:
How does a skip list work?
For a homework assignment, I need to understand how a skip list works.

I've been programming for a little over 2 years now (I know that's not that long in reality), and I have never even heard of a skip list.

I've looked over all of the guides that I can find, and I still only barely understand how they work. I even searched Code Review for an example implementation, and found only one review; and it's not even a complete implementation. I looked over the sample implementation supplied by the course, and it's absolutely atrocious. Between the lack of proper methods, and single-letter variable names, I have no clue how it works.

How does a skip list work? Is knowledge of a skip list required to understand more advanced data structures?

答:
In the olden days during data structures class, we learned how AVL trees worked. I would have had that in one of my classes, but the instructor said "you'll never actually use this" and instead had us learn 2-3 trees and b* trees instead. Those were days when memory was tight and processes were singly threaded. You didn't use a deque when a singly linked list would work just as well.

The skip list is much more common today with more available memory and concurrency not being an issue (you don't need to lock much at all when acting as a writer in a skip list - compared to everything with an AVL tree).

Frankly, it's my favorite data structure now in that it's something I can easily reason about how it works underneath and where it will be advantageous or disadvantageous to use.

You aren't going to need to write one from scratch (unless you get it as an interview question - but then you're just as likely to get implement an AVL tree).

You are going to need to understand why you want to select a ConcurrentSkipListMap in Java rather than a HashMap or TreeMap or any of the other map implementations.

To understand how it works, you need to understand how a binary tree works.  Wait, let me amend that.  You need to understand how a balanced binary tree works. Without balancing a binary tree, you don't get any real advantage with its lookup.

Lets say we've got this tree:

And we insert an '8' into it.  Now we've got:

And that's not balanced.  So, we go and do the magic of balancing it via some implementation...

And you've got a balanced tree again.  But that was a lot of magic I waved my hand over.

Lets take a skip list.

This one happens to be an idealized one.  Few are, but it shows the balanced binary tree nature that the skiplist ideal approximates.

Now, we want to insert a 6 into there.  This is inserting it much like a linked list.  However, we start at the top and go down.  The top points to 5.  Is 6 > 5? Yes. Ok, the top points off to the end now, so we go down the stack (we're on the 5).  The next is 7.  Is 6 > 7? Nope.  So we go down a level and we're at the base level so we insert 6 to the right of the 5.

We flip a coin - heads we build, tails we stay.  Tails.  Nothing more needs to be done.

Lets insert that 8 now.  8 > 5? yep.  8 > 7? Yep. And now we are at the bottom level again after following arrows and the stack around and we test 8 > 11? Nope. So we insert the 8 to the right of the 7.

We flip a coin - heads we build, tails we stay.  Tails.  Nothing more needs to be done.

In the balanced tree, we'd be getting all worked up about the tree not being balanced now.  But this isn't a tree - its a skip list. We approximate a balanced tree.

Now lets insert a 10. I'll avoid all the comparisons.

We flip a coin - heads we build, tails we stay.  Heads! And flip it again, Heads again!  Flip it again, ok, there's a tails.  Two levels above the base linked list.

The advantage here is that now if we're going to insert a 12, we can skip from 5 to 10 without doing all those other comparisons.  We can skip over them with the skip list.  And we don't have to worry about the balanced tree - the probabilistic nature of the stacking does that for us.

Why is this so useful?  Because when inserting the 10 I can do that by locking the write on the 5 and 7 and 8 pointers rather than the entire structure. And while I am doing that, the readers can still be going through the skip list without having an inconsistent state.  For concurrent usage, its faster not having to lock.  For iterating over the bottom layer, its faster than a tree (the joys of the BFS and DFS algorithms for tree navigation - you don't have to worry about them).

Will you encounter it? You'll probably see it in use in places. And then you'll know why the author chose that implementation rather than a TreeMap or HashMap for the structure.

Much of this has been borrowed from my blog post: The Skip List

Title: How does a skip list work?


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答:
I think the ubiquity of regex is due to the ubiquity of strings.  The string is the simplest data structure, the first one that most of us learn.  Since all of our code is written in symbolic form, it is natural for a programmer to consider modelling something in symbolic form.  But if our programming language offers any resistance when we try to extend its syntax for our clever new symbolic forms, they all end up between quotes.  The relational data model has SQL.  The XML data model has XQuery.  But what about the humble string data model?  Regex!

Just yesterday, I was looking over the API for a shiny new Javascript framework that supports HTML5 game development.  It has a declarative mechanism for describing the main subsystems that your game would need.  How does one specify those features?  JSON?  Fluent dot notation?  An array?  Nope -- a string containing a comma- and whitespace-separated list of feature names.  I wonder how it parses that list... ?


问:
What does pi mean in this BFS algorithm pseudocode?
I have the following pseudocode for breadth-first search algorithm

BFS(G,s)
 1 for each vertex u ∈ V(G) \ {s}
 2     color[u] = white
 3     d[u] = ∞
 4     π[u] = nil
 5 color[s] = gray
 6 d[s] = 0
 7 π[s] = nil
 8 Q = ∅
 9 Enqueue(Q,s)
10 while q ≠ ∅
11     u = Dequeue(Q)
12     for each v ∈ Adj[u]
13         if color[v] == white
14             color[v] = gray
15             d[v] = d[u] + 1
16             π[v] = u
17             Enqueue(Q,v)
18     color[u] = black
```

Original image

I do not understand what the letter π indicates in this context. I am not familiar with this algorithm and it is a difficult to guess.

I think d indicates the distance, color is of course the color, but that π... it appears to be a variable of some sort but I do not understand its function in this pseudocode.

答: The π vector surely keeps the node u with which you came in node v. This helps when you have to build the BFS tree of the graph. Although it is not necessary, this technique reduces a lot the complexity when you have to perform more time the BFS (ex. the Edmonds–Karp algorithm for computing the maximum flow between two nodes in a graph). In this case you don't have to run the BFS more times as you already have the BFS tree constructed and traverse it from the leaves to the root.</p>