答:
It is a lot easier if you write the code as

```<code>1  if condition
2  then
3      statement_1
4  else
5      statement_2
6  endif
</code>```

1 is the if-clause

2 and 3 are the then clause

4 and 5 are the else clause

In some languages, they use {}.  In those terse languages, then is considered a noise word so it is dropped.  In those languages, there is no then clause - 1 & 3 make up the if clause.  Those using indentation only (like python) don't have a then or endif.

Title: In an if statement, what are an "if clause" and a "then clause"?

Body:
I am a bit confused about the nomenclature for the parts of an if statement. Consider the following example:

```<code>1:  if condition then
2:      statement_1;
3:  else
4:      statement_2;
5:  end if;
</code>```

What is the "if clause" in this statement? Here are a few possibilities:

Is it lines #1 and #2?

Is it line #1?

Is it line #2?

Is is the condition in line #1?

And in the same example, what would be the "then clause"?

Is it line #2?

Is it the then keyword, plus line #2?

Is it just a synonym for "if clause"?

My main reference is Code Complete 2nd Ed., but the author seems to use exclusively the term "if clause", with the meaning being lines #1 and #2 in this example.

Body:
It is a lot easier if you write the code as

1  if condition
2  then
3      statement_1
4  else
5      statement_2
6  endif

1 is the if-clause

2 and 3 are the then clause

4 and 5 are the else clause

In some languages, they use {}.  In those terse languages, then is considered a noise word so it is dropped.  In those languages, there is no then clause - 1 & 3 make up the if clause.  Those using indentation only (like python) don't have a then or endif.


问:
Dealing with an often occuring dependency that is not related to the class
I'm using view classes for my templating. These view classes often require the Routing class to get URI's from other pages. You could actually say that the Routing should be available to every view class.

What I'm wondering how would you deal with the dependency injection. Injecting it through the constructor would mean that you will have to include it with every view class in many controllers. This would seem wrong to me.

You would also include it trough class extending but I don't think all views deserve a base class for just the routing library and it would able break the SOLID rules you do it because of a dependency that is not directly related to the child class.

My last option would be injecting it trough a public variable that injects it at a single place just before the template rendering.

How did you guys solve this problem? I'm looking for a clean non repetitive way.

答:
It sounds like you're describing a Cross-Cutting Concern.

Without knowing what exactly you mean by "clean, non-repetitive way" in the context of your problem domain, I can't really suggest any concrete solutions. Frameworks that enable AOP-like stuff such as DynamicProxy and PostSharp may address your issue, but again, I can't really say for sure without knowing exactly what you're looking for.

What I can say though is that if you have applied DI correctly and consistently, the dependency you speak of will be interchangable and the class which uses the dependency will be easy to unit test. In most scenarios, this makes the code sufficiently maintainable. So I wouldn't worry too much about the fact that a certain dependency recurs in multiple classes because that's OO programming for ya :)

ContentLicense: CC BY-SA 3.0


问:
Why use partial classes?
In my understanding, the partial keyword does nothing but allow a class to be split between several source files. Is there any reason to do this other than for code organization? I've seen it used for that in generated UI classes.

It seems a poor reason to create a whole keyword. If a class is big enough to require multiple files, it probably is doing too much. I thought that perhaps you could use it to partially define a class for another programmer somewhere to complete, but it would be better to make an abstract class.

答:
I can think of a few useful scenarios where partials make sense, most of them I am using myself in my projects:

To separate Tool/IDE/Designer generated code from the code you are maintaining. A good example is the Form.Designer.cs file that contains the designer generated code for windows forms applications. Many other .NET formats also have some tool generated code, which can be potentially regenerated when you build your project, and thus all your custom changes will be swiped out. The separation will help you keep your code and changes safe from such automated modifications.

When you are implementing multiple interfaces with a lot of code in the implementation. I tend to use a separate partial file for each such interface, naming it like this: {Class}.{Interface}.cs. It is easy for me to see in the IDE which interfaces the {Class} is implementing and how.

When the class must contain one or more nested classes, especially with enough code in them to be put into a separate file. I would stick to the above pattern and use the {Class}.{NestedClass}.cs naming convention for each nested class. Similar practice is already mentioned by Virtlink's answer.

When I write static classes which will hold extension methods. It will often be the case to provide the same extension method logic to similar classes or interfaces - like for instance Reverse on generic and non-generic collections. I would put all the extension methods for a single class or interface in a separate partial of the static class. For instance, I'd have all extension methods for the IList interface in one place, and the same methods that are for IList<T> in another file. Another approach would be to put the same method (all of its overloads) in the same partial, with all possible classes for the this parameter - like having all the Reverse implementations in one file. It depends which one would better justify the separation in terms of code volume, or some internal conventions you or your organization might be sticking to.

I do not use this, but I've seen some C/C++ folks to like the approach I will describe here: create a partial for the class with partial methods only. This resembles the C/C++ way to define interfaces and separate the method declaration from the implementation.

Separation by purely logical concerns. If you happen to work with a large class that combines more than one logical set of operations in itself, then you could separate each logically-related code into a separate partial. Usually existence of such classes is against the separation of concerns principle, but it is oftenly observed real-life case, especially for older codebases. Fellow user Steve Evers has mentioned them in his answer to this question, referring to them by the name god objects. I'd personally use the approach of partial classes to split the code before any refactoring of such really large files takes place, in order to ease my work and make the refactoring more transparent. This will also reduce the conflicts I will potentially cause when versioning systems like SVN are involved.

Title: Why use partial classes?


问:
How to implement differential backups without keeping copies of the original files on disk?
I am responsible for the design and development of a cloud backup application. Currently we are using xDelta to do differential backup so that only the changed parts of the files gets uploaded. This cuts cost for both us the company and the user. One issue we are having with this approach is that in order to do a differential backup the modified file needs to be compared to the original file. To solve this we opted for a quick solution and that is to cache the original files on the users' computer for a quick reference.

Now this solution works brilliantly for desktop/home users where the file sizes are relatively small. The problem arise when say a server administrator tries to backup an sql database for example that is 100GB in size. Though currently we cache the file on disk, this is definitely not appreciated by server administrators since we are filling their drives with cached files.

I am wondering if there is any other approach to do differential backups without the need of having the original files on disk permanently.

答:
It is really important when implementing a backup solution that the focus is not on the backup process, but on the restore process.  It is the ability to get the data back into a working environment that matters, not the filling up of cloud hard drives and LTO tapes.

In that respect, when backing up databases, OS directories, MS Exchange etc...  taking the 'grab the files' approach is just storing trouble for later.

With Databases if you do a byte by byte copy of the working files on an in use database then the result is likely to be a corrupt database when you attempt  the restoration.  If you make a shadow copy of the working files (and manage to get a consistent set with the shadow creation occurring simultaneously across all data files for that database) then you are providing a restoration option that is equivalent to recovery after a power off event.  In that most of the time the database software will recover, but you will still have a failure rate of 1-10%.

The only safe way to back up database is to trigger a database backup in the database software.  There are specific API's to trigger this, that can be done as part of the backup process which vary from database to database, but this will generate a backup file that WILL enable the database to be recreated again.  This is the data that needs backing up.  It will be new data each time so there is little point in doing differential analysis.

That said, companies using your services for this, would probably be better with a SAN supplying disks to virtualisation servers as iSCSI and implementing their infrastructure that way.  When it comes to restoration, the success rate of restoring a virtual OS environment is much higher than to bare metal, considering that it is highly likely to be restored to different hardware with different device driver needs.


答: I would create an interface IRoutingAware with method SetRouting that allows outside code to inject the routing instance. Then each view that implements this interface would have method called from the outside before the view is rendered. This would be even better if you had single place where the views are rendered, you just need to add two lines of code. In C#, the setting function could be implemented explicitly, which would make it obvious that the method shouldn't be called manually.

Title: Dealing with an often occuring dependency that is not related to the class

Body:
I'm using view classes for my templating. These view classes often require the Routing class to get URI's from other pages. You could actually say that the Routing should be available to every view class.

What I'm wondering how would you deal with the dependency injection. Injecting it through the constructor would mean that you will have to include it with every view class in many controllers. This would seem wrong to me.

You would also include it trough class extending but I don't think all views deserve a base class for just the routing library and it would able break the SOLID rules you do it because of a dependency that is not directly related to the child class.

My last option would be injecting it trough a public variable that injects it at a single place just before the template rendering.

How did you guys solve this problem? I'm looking for a clean non repetitive way.


问:
How to manage a single branch
I read the Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation book by Jez Humble and David Farley. The part that throw me off balance the most was their insistence on using a single branch.

Thinking about it and what they are preaching, it does make sense. But the question is, how to achieve it?.

At my company we are working on C# with TFS as our source control. And the following ideas came to my mind about how to achieve the idea of doing changes that you don't want to release yet, but you want to keep inside the vcs tool:

Injections to be able to select the class that you want to use. So you can rewrite some functionality without affecting code that needs to be released.

Related, an IoC container to make the above easy to achieve. So you can select at compilation (or even runtime) the ones that you want to use.

Decorator pattern to add functionality in a very simple manner (which is just applying the other two above)

At another similar question they talk about the Release Line from Software Configuration Management Patterns (which I still have to read). But the example that they are using deals with tags and creation of branches from them, which doesn't seem to be the same thing as what Humble and Farley talk about.

Do the techniques that I have described sound right for achieving a single branch strategy?

Is there anything else that could be done to manage having your code on a single branch?

答:
Multiple developer branches work just as well as a single branch - better in many cases. You might need to use a better tool for the job that TFS, but now it has git backing it that should do fine.

I would not attempt to change the software architecture to suit your build process, its the wrong approach - the software is the thing that matters, keeping it easily maintainable is much more important than suiting some process that is there to serve the software (not the other way round)

The trick with branches is to merge them into the trunk as soon as possible, and not to branch off new work until they are really needed. The other thing to do is to reverse-merge the trunk onto your branches (ie as changes from branches are merged onto trunk, developers working on their branches need to merge these changes to their branch, so they are very closely up to date) Then merging a branch to trunk becomes a trivial task.

Even with code that will sit around an not be merged for a long time, this is still ok - what it does mean is that the merge will become harder to accomplish as time goes on, but no amount of architectural changes to your code will help here - someone makes a change to the codebase and a year later you decide you need that code... I guarantee it won't work properly without manual intervention and refactoring of the code into what the trunk now looks like. What you need to do with this old code is a 3-way diff, so you can see the changes that were made to the original code, and apply those changes (or the important parts of them) to the new branch. Think of bringing the old code to the new as a development task rather than a build manager merging task.

Title: How to manage a single branch


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答: POKE in BASIC...</p>

ContentLicense: CC BY-SA 2.5

Body: POKE in BASIC...


问:
Has there been any formal proof that documentation in general is incomplete and obsolete to a certain grade?
I'm a web developer and I'm currently once again in a situation where a partly clueless ops department requires a "complete" documentation required for technical support of our application by a third-party, including "every possible error situation". Since there is no common ground on what this third-party should be capable of (ops constantly talk about "a person from the street should be able to do it"), I consider such documentation impossible and my experience tells me that every documentation is obsolete and incomplete, even if just a bit. I can't help to wonder: has there been any study or maybe even a proof that this is actually the case? Maybe even Gödel's incompletness theorems could be applied here?</p>

答:
I don't know of any formal proof, but here are some suggestions to solve your real problem. You are thinking about this too much like a programmer. Don't take  "every possible error situation" literally, when we all know you can't possibly document things you are not aware of. In your mind it sounds like they are requiring a perfect document. Whether there is definitive proof or not, you've already concluded it is impossible in this situation.

Someone needs to have a discussion about what they are really asking for and what you are able to create and come to some agreement.

Even if a code base doesn't change, there are application where users adapt the functionality by doing things the designers never imagined. It will be difficult for a lot of support staff to think about different ways the app can be used and how to support it.  Example: I worked as head of support for a water billing software company and a customer asked one of our initial support staff people if they could bill for trash. It was a flat-rate and our app had the ability to customize the label on each fee. In my mind it was obvious, flat-fee call it whatever you want.

Your documentation may have to adapt a bit of an agile approach to keep it up to date. Maybe this could be in the form of a wiki or some other type of website you can maintain and update frequently.  Of course they want the entire thing written up front and be perfect, but that isn't going to happen. You will need to make corrections and additions and that is going to be an on-going fee they're trying to avoid. Ask the client how often they are able to read the directions for anything and fully understand it? Software is much more complicated than putting together a bookcase.


答:
Producing such documentation is theoretically possible if:

The software remains static (or all changes are immediately documented)

All possible exceptions are caught and logged with their exact location in the code

The above exceptions have been caught in the wild and produce the expected output defined in the documentation

Forgive my crudeness, but you stand about as much chance of all this being true as a one legged man winning an ass kicking contest.

Code is rarely (if ever) perfect, documentation doubly so.

It sounds like your ops department is trying to absolve themselves of any responsibility if anything goes wrong. Errors happen despite best endevours and it is fantasy to try and convince yourself otherwise.

Title: Has there been any formal proof that documentation in general is incomplete and obsolete to a certain grade?

Body: I'm a web developer and I'm currently once again in a situation where a partly clueless ops department requires a "complete" documentation required for technical support of our application by a third-party, including "every possible error situation". Since there is no common ground on what this third-party should be capable of (ops constantly talk about "a person from the street should be able to do it"), I consider such documentation impossible and my experience tells me that every documentation is obsolete and incomplete, even if just a bit. I can't help to wonder: has there been any study or maybe even a proof that this is actually the case? Maybe even Gödel's incompletness theorems could be applied here?</p>


问:
Why have private static methods?
I just wanted to clear up a question I have. What is the point of having a private static method as opposed to a normal method with private visibility?

I would have thought an advantage to having a static method is that it can be called without an instance of a class, but since its private is there even a point to it being static?

The only reason I can think of is that it helps conceptually understanding the method on the class level as opposed to object level.

答:
The characteristic of being static is independent of the visibility.

The reasons that you will want to have a static method (some code that does not depend on non-static members) will still be useful. But maybe you don't want anyone/anything else to use it, just your class.

ContentLicense: CC BY-SA 4.0

Title: Why have private static methods?


答:
I can think of at least two reasons why you would need a static private method on a class.

1: Your instances have reason to call a static method you don't want called directly, perhaps because it shares data between all instances of your class.

2: Your public static methods have subroutines that you don't want called directly.  The method is still called without an instance, just not directly.

Of course, "it helps the class make sense" is a fine reason all on its own.

Title: Why have private static methods?

Body:
I just wanted to clear up a question I have. What is the point of having a private static method as opposed to a normal method with private visibility?

I would have thought an advantage to having a static method is that it can be called without an instance of a class, but since its private is there even a point to it being static?

The only reason I can think of is that it helps conceptually understanding the method on the class level as opposed to object level.


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
Send a final invoice with a cover letter threatening to initiate action in small claims court (or the English equivalent).

A little googling later, there IS an English equivalent: http://blogs.mirror.co.uk/investigations/howto/sue-small-claims-court.html

Note that you probably don't even have to DO the court claim. Hopefully just the threat will show him you mean business.

Title: How to get money from reluctant client?


答:
A fairly common reason (in Java) would be for initializing immutable field variables in a constructor by using a simple private static method to reduce constructor clutter.

It is private: external classes should not see it.

It is static: it can perform some operation, independent1 of the state of the host class.

A somewhat contrived example follows...

eg:

```<code>public class MyClass{
    private final String concatenated;

    public MyClass(String a, String b){
        concatenated = concat(a,b);
    }

    public String getConcatenated(){
       return concatenated;
    }

    /**
    *  Concatenates two Strings as `s1---s2`
    **/
    private static final String concat(String s1, String s2){
        return String.format("%s---%s", s1, s2);
    }
}
</code>```

1 Assuming it has no interaction with other static variables.

Title: Why have private static methods?

Body:
A fairly common reason (in Java) would be for initializing immutable field variables in a constructor by using a simple private static method to reduce constructor clutter.

It is private: external classes should not see it.

It is static: it can perform some operation, independent1 of the state of the host class.

A somewhat contrived example follows...

eg:

public class MyClass{
    private final String concatenated;

    public MyClass(String a, String b){
        concatenated = concat(a,b);
    }

    public String getConcatenated(){
       return concatenated;
    }

    /**
    *  Concatenates two Strings as `s1---s2`
    **/
    private static final String concat(String s1, String s2){
        return String.format("%s---%s", s1, s2);
    }
}

1 Assuming it has no interaction with other static variables.


问:
Why write tests for code that I will refactor?
I am refactoring a huge legacy code class.  Refactoring (I presume) advocates this:

write tests for the legacy class

refactor the heck out of the class

Problem:  once I refactor the class, my tests in step 1 will need to be changed.  For example, what once was in a legacy method, now may be a separate class instead.  What was one method may be now several methods.  The entire landscape of the legacy class may be obliterated into something new, and so the tests I write in step 1 will almost be null and void.
In essence I will be adding Step 3. rewrite my tests profusely

What is the purpose then to write tests before refactor?  It sounds more like an academic exercise of creating more work for myself.  I am writing tests for the method now and I am learning more about how to test things and how the legacy method works.  One can learn this by just reading the legacy code itself, but writing tests is almost like rubbing my nose in it, and also documenting this temporary knowledge in separate tests.  So this way I almost have no choice but to learn what the code is doing.  I said temporary here, because I will refactor the heck out of the code and all my documentation and tests will be null and void for a significant part, except my knowledge will stay and allow me to be fresher on the refactoring.

Is that the real reason to write tests before refactor - to help me understand the code better?  There's got to be another reason!

Please explain!

Note:

There is this post: Does it make sense to write tests for legacy code when there is no time for a complete refactoring? but it say "write tests before refactor", but doesn't say "why", or what to do if "writing tests" seems like "busy work that will be destroyed soon"

答:
My own answer/realization:

From fixing various errors while refactoring I am realizing that I wouldn't have done the code moves as easily without having tests.  Tests alert me of behavioral/functional "diffs" that I introduce by changing my code.

You don't have to be hyper aware when you have good tests in place.  You can edit your code in a more relaxed demeanor.  Tests do the verification and sanity checks for you.

Also, my tests have stayed pretty much the same as I refactored and were not destroyed.  I've actually noticed some extra opportunities to add assertions to my tests as I delved deeper into code.

UPDATE

Well, now I am changing my tests a lot :/  Because I refactored the original function out (removed the function and created a new cleaner class instead, moving the fluff that used to be inside the function outside of the new class), so now the code-under-test that I ran before takes in different parameters under a different class name, and produces different outcomes (original code with the fluff had more outcomes to test).  And so my tests need to reflect these changes and basically I am rewriting my tests into something new.

I suppose there are other solutions I can do to avoid rewriting tests. i.e. keep the old function name with new code and the fluff inside of it... but I don't know if it's the best idea and I don't have that much experience yet to make a judgment call on what to do.


答:
You see that you have a few lines of code that is repeated in a lot of your methods, so you decide to extract them to a single method, as duplicated code is not good.

You make the method private as it is not designed for widespread usage and you don’t want unrelated code calling it.   (Debate this point in the comments….)

As the method does not access any instance fields, it can be make static, by making it static you make it easier to understand and maybe even a little faster.

Then.... (Maybe now, maybe later, maybe never)

Once the method has been made static, it is clear that it can be moved out of the class, say to an unity class.

It is also easy to transform it into an instance method of one of its parameters, often this is where the code should be.

Title: Why have private static methods?


问:
Is XHTML5 dead or is it just an synonym of HTML5?
So what happened to XHTML5?

http://www.w3.org/TR/html5/

That page is a draft for both xhtml5 and html5?
So there's no difference between these doctypes?

答:
XHTML5 is a synonym for "HTML5 serialized as XML".

There are various concrete syntaxes that can be used to transmit resources that use this abstract language, two of which are defined in this specification.

...

The second concrete syntax is the XHTML syntax, which is an application of XML. When a document is transmitted with an XML MIME type, such as application/xhtml+xml, then it is treated as an XML document by Web browsers, to be parsed by an XML processor. Authors are reminded that the processing for XML and HTML differs; in particular, even minor syntax errors will prevent a document labeled as XML from being rendered fully, whereas they would be ignored in the HTML syntax. This specification defines version 5.0 of the XHTML syntax, known as "XHTML 5".

quoted from http://www.w3.org/TR/html5/introduction.html#html-vs-xhtml ; note that is also says "This section is non-normative.".

Also, there's a nice document on writing HTML5 polyglots (pages, that can be serialized both as regular HTML5 and XML) here:

http://dev.w3.org/html5/html-polyglot/html-polyglot.html#bib-HTML5

And a validator even!

http://html5.validator.nu/

It's rarely called XHTML5 nowadays (and probably even more seldom used), since it's basically still HTML5, but it's still there.

Simply put: every change to HTML5 spec is also an implicit, corresponding change to XHTML5.


答:
A common use-case for a private static method is a utility method which is

only used by that one class

is independent of the internal state of that class

Title: Why have private static methods?


问:
System Communication: Avoiding Including a Large "HAS-A" Hierarchy Which Isn't Used
The situation:

System A

Huge, complicated system.  Uses an important Message object with many other Message objects attached, many of which have further Message objects attached.  In total, this is about twenty different objects.

Due to awkward timing with releases and introduction of code churn, System A cannot have its Message object hierarchy touched.

System B

Needs to use the same important Message object to communicate with System A to make use of one of its services.  However, since the messages it will send off are going to be invariable, it only uses a very small portion of the Message object hierarchy.

The Question:

How could I allow System B to make use of the important Message object without (a) touching System A, or (b) including a hierarchy of nearly twenty objects, almost none of which are used at all?  Is there a more advanced Design Pattern which could be put to use in this scenario?

答:
Use Facade (or possibly Adapter) to create your own internal interface into the message system, and wrap it around & hide the external message classes.

http://en.wikipedia.org/wiki/Facade_pattern

At test time, this makes it easy to stub or mock, because you only have to make fakes for your facade.

At run time, the facade can interact with the real, complicated, redundant heirarchy transparently. You decouple your code from the external implementation.


问:
how and should I 'unit test' an entire package?
I'm still learning to be good about doing unit level testing, as I've always been a little sloppy about only doing functional testing in the past, so I want to double check I'm doing this 'right'.

I have a package which is responsible for auto-magically updating a particular configuration which is expected to change regularly during runtime.  Provide a list of objects to monitor to the constructor of my main package class.  Then at some point call update it will go to all the multiple places that define configuration, detect change, update the appropriate state for the objects it's monitoring, and provide a report of what was changed.  This is all automatic and otherwise transparent to all other packages.

My inclination is to test this as a unit, but it is a pretty 'big' unit, 5-6 classes and fetching from multiple files and a restful interface.  It feels like testing any smaller units would take much longer, be less flexible to refactoring and only provide a slightly higher chance of detecting a defect, but that could just be my laziness talking.  Would it be considered 'better' to test at a lower level?

Assuming it is 'right' to test the package as a unit what is considered appropriate for mocking something like this?  There are methods of classes which are instantiated by my main class (ie, not something I pass in directly so I can't just pass my own mock) that have methods I want to control.  I believe I can use powerMock in the two cases I can think of (or could, after I research PowerMock some more), but I'm not sure if doing so is transparent enough.  Is configuring PowerMock to detect and return a mock file object any time my package tries to open a configuration file, even if it's buried deep in my package logic, acceptable, or is this considered to be abusing my knowledge of implementation specific details?  Would it be 'cleaner' to actually modify configuration files on the file system and let them be read normally without further mocking?  I would need to modify the files regularly for testing...

Edit:
To clarify the question of coupling asked in one of the questions, I don't think that my classes are overly coupled.  Effectively I have three classes that fetch state from A, B, and C, and then a 'main' class which takes the state from the three and decides how to combine it correctly (ie, if A and B don't match use A unless C).  I could easily test A B and C separately and then mock them to test my 'main' class.  However, it seems like the testing of my 'main' class would effectively test the comparatively simple interfaces for A, B, and C anyways if I didn't mock them.  Thus it feels like duplicate work to test them individually.  I may get some slightly better code coverage, maybe, with individual testing, and it's always nice to have one test test only one thing.  But I don't know if it's worth all the overhead for minor benefits.

答:
Unit testing is like inductive reasoning. You ensure that the small piece n is well-behaved, and then can trust that as you build up the system, each n + 1 piece is also well-behaved.

In your case, I would isolate as many of the 5-6 classes in individual testing to make sure that each one is doing what it should. (That has an extra benefit of speeding up your coding, because you're not always tripping over unexpected defects.)

If you then want to test those working together in isolation, that's good -- just consider what you need to mock or stub to kick off specific logic paths. At some point, something is calling into your system to trigger the update -- so mock that out.

A good rule of thumb is, don't test something you didn't write -- mock it.

On a more philosophical level ;) the definition of "unit" isn't a bright line. A unit can be a method, or a class, but even within a method, there's probably references to multiple objects. As long as you can draw a reasonably small boundary around the "unit" and run it in isolation, it's all good.

...

Another consideration is that if your 5-6 small classes are easy to unit test individually, then they are mostly likely well designed. If those classes are tightly coupled enough that you can't exercise each in isolation, it means you probably need to step back and look at your design.


答:
Generally, if I find I'm writing private static methods, I take it as an indication that there's something I should have modeled separately.

Since they're not tied to the state of a particular object instance, a collection of public and private static methods could form an entirely separate class with its own semantics & non-static methods.

(Another tip-off is if I find I have a lot of static methods (public and private) that all have a common parameter of some type, they might be better off as members of that type.)

So, to answer your question, private static methods appear when a class provides a group of related methods that are independent of an instance of that class. (...and since they're independent, they may be better off in their own class.)

Title: Why have private static methods?


问:
How to capture "Display advertisement" use case?
What kind of use case it would be for to "show ad in part of the view"? Who could be the actor to relate with? User or System? As user has no specific goal to see ads, i am wondering what is the best way to capture this in use case diagram?

Any assistance will be helpful

答:
I would imagine it would look very much like any other use case.

http://msdn.microsoft.com/en-us/library/dd409432.aspx

In the above diagram, substitute "Advertiser" for "Restaurant," and "User" for "Customer."  Change one of the circles to "Serve Advertisement."


问:
Breadth-first graph search problem
I thought I was doing breadth-first graph search correctly, but my instructor's grading script is telling me that my answer is incorrect.

From the instructions:

Consider a breadth-first graph search on the graph below, where S is the start and G is the goal state. Assume that ties are broken alphabetically (so a partial plan S->X->A would be expanded before S->X->B and S->A->Z would be expanded before S->B->A). You may find it helpful to execute the search on scratch paper.

Please enter the final path returned by breadth-first graph search in the box below. Your answer should be a string with S as your first character and G as your last character. Don't include arrows or spaces in your submission. For example, if you believe the path is S->X->G, please enter SXG in the box.

I got and input the answer SACBG, which the grading script marked as incorrect. ("Your input was evaluated as SACBG, which is not correct.")

Here are my steps for the breadth-first graph search on the above graph using the algorithm at http://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode:

Enqueue the root node S. Queue = [S], Path = []

Dequeue S and examine it. Queue = [], Path = [S]

Enqueue S's children, A and C. Queue = [A, C], Path = [S]

Dequeue A and examine it. Queue = [C], Path = [S, A]

A has no children. Dequeue C and examine it. Queue = [], Path = [S, A, C]

Enqueue C's children B and G. Queue = [B, G], Path = [S, A, C]

Dequeue B and examine it. Queue = [G], Path = [S, A, C, B]

B's only child G is already in the queue. Queue = [G], Path = [S, A, C, B]

Dequeue the goal node G and examine it. Quit the search and return. Queue = [], Path = [S, A, C, B, G]

A node is placed in the path when it is dequeued and examined.

Ties are broken alphabetically as required in the instructions.

What am I doing wrong?

答:
Since nobody provided the details yet, here is your answer with correction:

Enqueue the root node S. Queue = [S], Path = []

Dequeue S and examine it. Queue = [], Path = [S]

Enqueue S's children, A and C. Queue = [A, C], Path = [S]

Dequeue A and examine it. Queue = [C], Path = [S, A]

-> All correct so far

A has no children. Dequeue C and examine it. Queue = [], Path = [S, C]

-> This is where the mistake was: A is removed from the path, as well, since it has no children; the search switches from path S-A (a dead end) to path S-C now.

Enqueue C's children B and G. Queue = [B, G], Path = [S, C]

-> Correct, except the current path is S-C (not S-A-C).

Dequeue B and examine it. Queue = [G], Path = [S, C, B]

B's only child G is already in the queue. Queue = [G], Path = [S, C, B]

-> Correct, with the same correction as above (A is not in the path anymore).

Dequeue the goal node G and examine it. Quit the search and return. Queue = [], Path = [S, C, G]

-> Dequeue G and examine it, find it's a goal, stop. Same mistake as above: B is removed from the path, and the search switches from path S-C-B to S-C-G (which happens to be the solution path).

Note that, if all edges have the same weight (of 1, as is your case), then breadth-first search finds the shortest path (minimum number of steps).

Title: Breadth-first graph search problem


答:
You could argue that truly complete documentation - documentation that describes exactly what the software does with every filesystem, network, and UI input and output and every error condition and corner case - is as detailed as the source code and effectively indistinguishable from source code.  After all, source code is nothing more than a machine-readable description of how the software should make all of those decisions.

I doubt your clients want the source code or want to pay you to duplicate the source code.  For bonus points, consider that a great deal of your application's behavior depends on its operation system, libraries, and frameworks and that complete documentation would therefore cover those as well.

Like @JeffO and @DocBrown said, though, taking this approach is probably applying overly literal programmer-thinking to a user relations question, and the better approach is to try to discover and address their underlying concerns.


问:
xaml schedule control how to cope with items of vastly differing durations
I have to create a schedule control using WPF XAML for displaying items with duration as little as 1 seconds and potentially as large as couple of hours.

First thing which seems clear is that I will need some kind of zoom capability, for drilling into the items with very short durations and zooming out to view the items with very large durations.

I have a UI style in mind where by when the control is zoomed to view the large items, any small duration items which generally occur between the large duration items are some how collected in to a 'bucket' which has a height >= a minimum display height.  So that I can perhaps hover a mouse over this bucket and get a tool tip which renders the contained items into a time ordered list view.

I am at a loss as to where to begin.  I feel that I could perhaps achieve something in the Measure/Arrange overrides of a custom Panel.  But I think this could adversely affect render performance.  If I were to do it this way,  I guess I would need to inject a 'bucket' view into the panels children collection, but that would break the use of ItemTemplate in my Custom Items Control?

My second though is that I create a custom observable collection which has a bindable Scale property which then organises the collection into 'buckets' of a duration large enough to be displayable.

Does anyone have any thoughts on how I should best approach this problem?

答:
I've created a scheduling control in WPF and you're right about using the Measure/Arrange overrides of a panel for part of your work.

There's a great series of blog posts where the author goes over the making of just the same thing.

For zooming, I created a ZoomCommand that could be bound to any gesture to allow a user to zoom in and out. (Works great with WPF's support for pinch to zoom). I think walking through this series should give you a great place to start.


问:
What graph traversal algorithm should I use?
I would like to write an algorithm which can traverse a graph and hopefully later I can implement it to use for an indoor navigation system.
The graph would come from floor plans of a building and the graph nodes represent the building objects such as doors, corridors, stairs, rooms, etc.

The navigation system will accept different users with different capabilities, these capabilities are stored in user profile. For each individual user (or a group of users of the same type, e.g. staff member) the system returns a path specific to that user/s considering his personal functionality. For example if the user of the system is using a wheelchair the system should exclude all the stair nodes from the path (they will be marked non-traversable). Similarly if in order to enter into an indoor space, the user needs to have a key or be an staff member but he is NOT, the system should mark the node (e.g. the door  which requires the key) non-traversable and should search for those paths which don't require these specifics requirements.

This was the first part and here I use a function to check these conditions for a given user. The inputs to this function are a node and a user. If the conditions that are required by the node are NOT fulfilled (means user profile doesn't match the condition required by the node) the function returns false= non-traversable.
 If the condition holds true, the node stays isTraversable and will be stored somewhere and will be considered for the final path calculation.

The second part is that I have a list that contains all the nodes that are traversable and now the shortest path will be calculate based on 3 different costs, Energy, time and money. The final cost can be a combination of these costs and it sets the weights for the edges.

My problem is with the first part. I want to know how can I make an algorithm that produces the subgraph (the list with the traversable nodes in it). And later how can I use this algorithm to modify Dijkstra to fit this system.

Can anybody help with writing a pseudocode for the algorithm so that I can understand how would it work in clear steps or any hints on how can I make these steps into pseudocode?

Please note that at this stage the performance is not very important for me.

答:
With all due respect, I find most answers and comments so far kind of confusing, and there is no straight answer yet. For instance there is no point speaking of heuristics (thus of A* algorithm) since we do not have any information to help guide the search, and besides the issue as clearly stated is not search or performance, but the matter of node traversability.

Also, the trick of setting a high cost for non-traversable nodes works to some extent but... The problem is that those nodes will still remain in the graph, and will be searched like any other, which will affect performance later on. The other issue is that a high node cost won't help if there is no other solution path; in such case a path might be found that goes through a non-traversable node (which would clearly be a major "bug" with the program!) So for both reasons it is a must to remove non-traversable nodes.

Now, given the problem as stated, and since the author knows Dijkstra algorithm (which is the most appropriate for the given scenario anyway), it is simply a matter of modifying the part of the algorithm that generates the children of a node and inserts them into the queue. That is, instead of enqueuing them all, unconditionally, we can use the user-specific isTraversable function to determine which to enqueue and which to discard.

Below is some pseudocode (largely adapted from cprogramming.com), with the additional test you need in uppercase:

```<code>/* Given graph G, with edges E of the form (v1, v2) and vertices V, and a source vertex s
*
*  dist : array of distances from the source to each vertex
*  prev : array of pointers to preceding vertices
*  i    : loop index
*  U    : list or heap of vertices
*/

/* Initialization: set every distance to INFINITY until we discover a path */
for i = 0 to |V| - 1
    dist[i] = INFINITY
    prev[i] = NULL
dist[s] = 0    /* The distance from the source to itself is zero */

/* Examine the many alternative paths, always picking "the vertex, v, with the
 * shortest path to s" first, to guarantee finding the optimal solution */

while (U is not empty)
   pick the vertex, u, in U with the shortest path to s
   if u is the goal
        return u
   if dist[u] is INFINITY
       return error: no solution
   remove u from U
   for each child node v of u  /* edge (u, v) */
        if v is in U
            IF v IS_TRAVERSABLE
                if(dist[u] + length(u, v) < dist[v])
                    dist[v] = dist[u] + length(u, v)
                    prev[v] = u
            ELSE
                remove v from u
</code>```

Body:
With all due respect, I find most answers and comments so far kind of confusing, and there is no straight answer yet. For instance there is no point speaking of heuristics (thus of A* algorithm) since we do not have any information to help guide the search, and besides the issue as clearly stated is not search or performance, but the matter of node traversability.

Also, the trick of setting a high cost for non-traversable nodes works to some extent but... The problem is that those nodes will still remain in the graph, and will be searched like any other, which will affect performance later on. The other issue is that a high node cost won't help if there is no other solution path; in such case a path might be found that goes through a non-traversable node (which would clearly be a major "bug" with the program!) So for both reasons it is a must to remove non-traversable nodes.

Now, given the problem as stated, and since the author knows Dijkstra algorithm (which is the most appropriate for the given scenario anyway), it is simply a matter of modifying the part of the algorithm that generates the children of a node and inserts them into the queue. That is, instead of enqueuing them all, unconditionally, we can use the user-specific isTraversable function to determine which to enqueue and which to discard.

Below is some pseudocode (largely adapted from cprogramming.com), with the additional test you need in uppercase:

/* Given graph G, with edges E of the form (v1, v2) and vertices V, and a source vertex s
*
*  dist : array of distances from the source to each vertex
*  prev : array of pointers to preceding vertices
*  i    : loop index
*  U    : list or heap of vertices
*/

/* Initialization: set every distance to INFINITY until we discover a path */
for i = 0 to |V| - 1
    dist[i] = INFINITY
    prev[i] = NULL
dist[s] = 0    /* The distance from the source to itself is zero */

/* Examine the many alternative paths, always picking "the vertex, v, with the
 * shortest path to s" first, to guarantee finding the optimal solution */

while (U is not empty)
   pick the vertex, u, in U with the shortest path to s
   if u is the goal
        return u
   if dist[u] is INFINITY
       return error: no solution
   remove u from U
   for each child node v of u  /* edge (u, v) */
        if v is in U
            IF v IS_TRAVERSABLE
                if(dist[u] + length(u, v) < dist[v])
                    dist[v] = dist[u] + length(u, v)
                    prev[v] = u
            ELSE
                remove v from u


问:
Algorithm for Learning development
This is a fairly general question. I know a bit of Perl and Python and I am looking to learn programming in more depth so that once I get the hang of it I can start developing applications and then websites.

I would like to know of an algorithm (sequence of steps :)) that could describe my approach towards learning programming in general. I have posted small questions on Perl/Python and I have recieved great help from everyone.

Note:- I am not in a hurry to learn. I know it takes time and that's fine.

Please give any suggestions you think are valid. Also, please don't push me to learn Lisp, Haskell etc - I am a beginner.

答:
For every language you want to learn L

Step 1: Learn the syntax of L.

Step 2: Write a compiler for L in your favorite language.

Step 3: Write a compiler for your favorite language in L

Step 4: Write a major project idiomatically in L

Bonus: Make sure the result of Step 2 is compatible with the result of Step 4.

That should pretty much cover it, get back to us with a progress report in 10 years.

If all you're after is learning to do web development, and you already know Perl and Python, you pretty much have enough for a start. I'd say start learning the ins and outs of Apache (and specifically mod_perl and mod_python), then get practicing. Maybe pick up a book or two on CGI programming, network communication and such, rather than specific language manuals.

As a final note, being a beginner is no reason not to learn Lisp. Go check out SICP and the video lectures. Neither assumes any level of expertise with development, or computers. In fact to quote the introduction to the video lectures

I'd like to welcome you to this course on Computer Science. [Writes it on the board] Actually that's a terrible way to start. Computer science is a terrible name for this business. First of all, it's not a science [crosses out "science"]. It might be engineering or it might be art. [...] It's also not really very much about computers [crosses out "computer"]. And it's not about computers in the same sense that physics is not really about particle accelerators. And biology is not really about microscopes and petri dishes. -Hal Abelson

Title: Algorithm for Learning development


问:
How to avoid programmers duplicating code
While I know in a perfect world where a greenfield application was scoped out from day one with great BRD's and a competent development lead constantly reviewed code by their underlings to avoid this, I'm going to ask because we all know and have all been a part of plenty of scenarios where this isn't the case... and this happens...

The problem I run into all the time with consulting gigs is you'll find ten methods all pretty much doing the same thing, and with some refactoring, could be much more efficient.  However, it doesn't seem to stop the developers from creating new methods when there's one already written, or mostly written they could use.

The problem doesn't always lie with the developer(s).  If it's a large application, and even in a Service Oriented Architecture scenario, you could have hundreds of services and you're bound to have duplicates there because the other developer needed to accomplish something, was being a good little coder in making a reusable class/method, but wasn't aware another good little developer has already created that method.

So my question to you all is, what have you found to be the most successful way in avoiding duplicate methods?  Documentation, Communication, Automated Refactoring?  But more important, how to clue in other developers coming into an existing application project with all the methods and services available to them?

答:
Some ideas;

Clear, well understood, code structure. So that there's an 'obvious' place to put certain code, by folder location or namespaces; if it's a shared extension method for example, then you might find those in a Company.Common.Extensions location. Or set patterns for encapsulation, so that methods should be found inside a relevant type, not externally in "BlobManager" classes. This will help them find existing code if it exists.

Unit tests; often devs might feel a method doesn't do exactly what they need, and rather than touch existing code they'll roll their own. Appropriate Unit Tests can aid in a refactor to get existing code changed without breaking current behaviours

Code Reviews; maybe awareness is the issue, and a code review helps spread awareness in a team

Set expectations in the team that duplication is not appropriate, and enforce that through reviews and refactoring.

OwnerDisplayName: Indy-Jones


问:
Advantages of using the library PyContracts over assert statements
Today I stumbled upon the python package called PyContracts. However, python has the assert statement which seems to allow you to do exactly those things. What advantages do contracts have over assert statements?

答:
Thanks for pointing out the existence of this interesting Python module. I checked it out and, in short, PyContracts is much higher level and powerful than mere built-in assertions, for checking function parameters and types.

Taking an example from the documentation itself, in the following, "PyContracts is smart enough to check that the two parameters a and b are matrices of compatible dimensions."

```<code>@contract
def matrix_multiply(a,  b):
    ''' Multiplies two matrices together.'''
    return numpy.dot(a, b)
</code>```

Note that the only statement added is @contract whereas, if using an assertion, one would have to explicitly compare the dimensions! For example:

```<code>assert a.shape == b.shape
</code>```

The next example, from the tour again, "checks that the two lists a and b have elements of the same type (indicated by the variable x) and also that the returned list has the correct size (the sum of the two lengths)!"

```<code>@contract(      a='list[ M ](type(x))',
                b='list[ N ](type(x))',
           returns='list[M+N](type(x))')
def my_cat_equal(a, b):
    ''' Concatenate two lists together. '''
    return a + b
</code>```

Quite amazing. Again the above could be done using assertions only, but then it'd be much more complicated! PyContracts is about making it easier and yielding more readable code.

On the other hand, this clearly does not replace the need for assertions within the body of a function or method. So the two are complementary tools...

Body:
Thanks for pointing out the existence of this interesting Python module. I checked it out and, in short, PyContracts is much higher level and powerful than mere built-in assertions, for checking function parameters and types.

Taking an example from the documentation itself, in the following, "PyContracts is smart enough to check that the two parameters a and b are matrices of compatible dimensions."

@contract
def matrix_multiply(a,  b):
    ''' Multiplies two matrices together.'''
    return numpy.dot(a, b)

Note that the only statement added is @contract whereas, if using an assertion, one would have to explicitly compare the dimensions! For example:

assert a.shape == b.shape

The next example, from the tour again, "checks that the two lists a and b have elements of the same type (indicated by the variable x) and also that the returned list has the correct size (the sum of the two lengths)!"

@contract(      a='list[ M ](type(x))',
                b='list[ N ](type(x))',
           returns='list[M+N](type(x))')
def my_cat_equal(a, b):
    ''' Concatenate two lists together. '''
    return a + b

Quite amazing. Again the above could be done using assertions only, but then it'd be much more complicated! PyContracts is about making it easier and yielding more readable code.

On the other hand, this clearly does not replace the need for assertions within the body of a function or method. So the two are complementary tools...


问:
One Event Sent to Multiple Listeners, Want to Log Notification Once

I have a system in place where a Cache is made up of many Cache Nodes.  When one is added, a CacheNodeAdded event is raised by the Cache.  The Cache has a redundant set of Monitors listening for this event.  Monitors are responsible for notifying on Cache events.

Since I have multiple Monitors, but only want to be notified once, Step 3 is what I am looking to implement.

Solutions I can't use:

Cache notifying directly.  Monitors must be used.

Have each Monitor check the log to see if the notification has been sent.  Since they all run separately, they could all access the list of notifications at the same time, see the notification hasn't been sent, and notify multiple times as a result.

Solution I'm toying with:

When event is received, get a list of all Monitor IDs (GUID), order the list, and the first Monitor in the list gets to send the notification.  This is a simple solution but it seems a little inelegant.

Are there any other simple solutions that I may be overlooking?

答:
I ended up implementing the solution discussed in my question.  </p>

<p>•When event is received, get a list of all Monitor IDs (GUID), order the list, and the first Monitor in the list gets to send the notification. </p>

Body:
I ended up implementing the solution discussed in my question.

•When event is received, get a list of all Monitor IDs (GUID), order the list, and the first Monitor in the list gets to send the notification.


答:
Unit testing is the lowest level of testing, but that means only that it is the lowest level you do, not the lowest level you could theoretically do. If you test at the class level, you could test at the method level, using an appropriate test tool to get at private members. But if you test at the method level, you could test at the statement level, using an appropriate test tool to get the statement in isolation so you test it. And if you did decide to test at statement level, that's still a decision not to test at instruction or byte code level. And that process of decomposition only stops when someone decides 'a smaller unit would be stupid'.

So the question 'how should I unit test this' is exactly equivalent to 'how should I first test this'. If the best way of testing a package is as a whole, because it is of a size and complexity where testing it as a unit is the most effective way of meeting your reliability and maintainability goals, then do so.

If it isn't, then don't.

Anyone trying to give more specific advice without either seeing your code base or knowing your project context (nuclear power plant in basement of an orphanage, or email spam generator?) is very likely not merely wrong, but also unwise.

Title: how and should I 'unit test' an entire package?

Body:
I'm still learning to be good about doing unit level testing, as I've always been a little sloppy about only doing functional testing in the past, so I want to double check I'm doing this 'right'.

I have a package which is responsible for auto-magically updating a particular configuration which is expected to change regularly during runtime.  Provide a list of objects to monitor to the constructor of my main package class.  Then at some point call update it will go to all the multiple places that define configuration, detect change, update the appropriate state for the objects it's monitoring, and provide a report of what was changed.  This is all automatic and otherwise transparent to all other packages.

My inclination is to test this as a unit, but it is a pretty 'big' unit, 5-6 classes and fetching from multiple files and a restful interface.  It feels like testing any smaller units would take much longer, be less flexible to refactoring and only provide a slightly higher chance of detecting a defect, but that could just be my laziness talking.  Would it be considered 'better' to test at a lower level?

Assuming it is 'right' to test the package as a unit what is considered appropriate for mocking something like this?  There are methods of classes which are instantiated by my main class (ie, not something I pass in directly so I can't just pass my own mock) that have methods I want to control.  I believe I can use powerMock in the two cases I can think of (or could, after I research PowerMock some more), but I'm not sure if doing so is transparent enough.  Is configuring PowerMock to detect and return a mock file object any time my package tries to open a configuration file, even if it's buried deep in my package logic, acceptable, or is this considered to be abusing my knowledge of implementation specific details?  Would it be 'cleaner' to actually modify configuration files on the file system and let them be read normally without further mocking?  I would need to modify the files regularly for testing...

Edit:
To clarify the question of coupling asked in one of the questions, I don't think that my classes are overly coupled.  Effectively I have three classes that fetch state from A, B, and C, and then a 'main' class which takes the state from the three and decides how to combine it correctly (ie, if A and B don't match use A unless C).  I could easily test A B and C separately and then mock them to test my 'main' class.  However, it seems like the testing of my 'main' class would effectively test the comparatively simple interfaces for A, B, and C anyways if I didn't mock them.  Thus it feels like duplicate work to test them individually.  I may get some slightly better code coverage, maybe, with individual testing, and it's always nice to have one test test only one thing.  But I don't know if it's worth all the overhead for minor benefits.


答:
The best thing I am aware of is communication. It contains some points:

Almost all classes or functions I reused from other programmers inside a project, came to my awareness, because I was talking with them about some issue and therefore knew that they had written something for it. Code reviews and pair programming can reinforce this.

Also the code has to talk to you, what I mean is, you need good naming in order to understand if this class or function is useful for you. Therefore, it should perform only one task, have one single responsibility. Forget other documentation, if it is not easy to understand no one dares to use it and again writes his own.

The team should agree to place reusable code, a good little developer has created, to some commonly known places everybody can look for it. Even just a simple tools/utilitys-class/file/namespace, is better then to place a helper-function next to the class that only you will ever maintain.

Title: How to avoid programmers duplicating code

Body:
While I know in a perfect world where a greenfield application was scoped out from day one with great BRD's and a competent development lead constantly reviewed code by their underlings to avoid this, I'm going to ask because we all know and have all been a part of plenty of scenarios where this isn't the case... and this happens...

The problem I run into all the time with consulting gigs is you'll find ten methods all pretty much doing the same thing, and with some refactoring, could be much more efficient.  However, it doesn't seem to stop the developers from creating new methods when there's one already written, or mostly written they could use.

The problem doesn't always lie with the developer(s).  If it's a large application, and even in a Service Oriented Architecture scenario, you could have hundreds of services and you're bound to have duplicates there because the other developer needed to accomplish something, was being a good little coder in making a reusable class/method, but wasn't aware another good little developer has already created that method.

So my question to you all is, what have you found to be the most successful way in avoiding duplicate methods?  Documentation, Communication, Automated Refactoring?  But more important, how to clue in other developers coming into an existing application project with all the methods and services available to them?


问:
Linked list clarification
This is a pretty simple question but I'm new to java.

The linked list found in java.util.LinkedList.

I saw elsewhere that Java does not use pointers...

When I create a new list and add new elements to it, does the list contain references to the data and to the next/previous elements or does it also contain the object itself.

答:
To answer specifically: note that java.util.LinkedList defines a doubly-linked list.

The list has two member variables first and last that reference ("point at") the first and last nodes. List nodes are of type Entry<T>, where T is the type of the objects you are inserting.

Each list node or Entry thus contains:

T data : the actual item (object) inserted

Entry<T> next : a reference to ("pointing at") the next node (null if last)

Entry<T> previous : a reference to ("pointing at") the previous node (null if first)

For example, list (A,B,C,D) is represented as follows:

```<code>/   \  ->  /   \  ->  /   \  ->  /   \
| A |      | B |      | C |      | D |
\   /  <-  \   /  <-  \   /  <-  \   /
  ^                                ^
first                            last
</code>```

Title: Linked list clarification

Body:
To answer specifically: note that java.util.LinkedList defines a doubly-linked list.

The list has two member variables first and last that reference ("point at") the first and last nodes. List nodes are of type Entry<T>, where T is the type of the objects you are inserting.

Each list node or Entry thus contains:

T data : the actual item (object) inserted

Entry<T> next : a reference to ("pointing at") the next node (null if last)

Entry<T> previous : a reference to ("pointing at") the previous node (null if first)

For example, list (A,B,C,D) is represented as follows:

/   \  ->  /   \  ->  /   \  ->  /   \
| A |      | B |      | C |      | D |
\   /  <-  \   /  <-  \   /  <-  \   /
  ^                                ^
first                            last


问:
Regular Expressions and Language Generators
I have few CS textbooks with me which discuss languages, well actually 2 plus old course notes supplied a few years ago. I have been searching the web too any only seem to come up with vague responses just like the text books I have.

My question is about language recognisers verses generators.

I get the overriding principle of a recogniser. That it analyses a language and is able to determine nay or yay if a String belongs to a language. This is at least what I have picked up from the books and notes. However, it's much more complex than that is it not? A tokeniser and syntax analyser (which I assume to be recognisers) do not just say yes or no, they also say where don't they...?

However, language generators. No one seems to be very clear about what they are. The typical description I get is For example Sebasta's Concepts of Programming Languages says 'A language generator is a device that can be used to generate the sentences of a language. We can think of a generator as a push button that produces a sentence of a language every time it is pressed.' Seriously? That's it?? Your kidding right....

I read that Regex is an example of a Generator, then why when people talk of generators do they not talk of the inputs. For example Regex has a target String, and the Regex with defines both the accepted alphabet and it's grammar rules.

Can someone provide for me a clearer distinction of what a recognizer is?

答:
I'm surprised you didn't find your answer in Sebesta's Concepts of Programming Languages... In short:

Recogniser: sentences -> grammar. Application: to check if given sentences are part of the language grammar. This is an essential part of a compiler or interpreter.

Generator: grammar -> sentences. Application: to provide examples of valid sentences in the language. This is an essential part of a programming language manual.

For instance, the user manual for a certain programming language may explain in words what a valid assignment looks like, and even provide a BNF rule (something like: assign -> var = expr), but it will also include examples of valid assignments so that the programmer understands better (e.g., a = b or x = y + 2*z). Such examples are generated from the BNF through a process known as derivation.


问:
Make methods that do not depend on instance fields, static?
Recently I started programming in Groovy for a integration testing framework, for a Java project. I use Intellij IDEA with Groovy plug-in and I am surprised to see as a warning for all the methods that are non-static and do not depend on any instance fields. In Java, however, this is not an issue (at least from IDE's point of view).

Should all methods that do not depend onto any instance fields be transformed into static functions? If true, is this specific to Groovy or it is available for OOP in general? And why?

答:
I think it is to enable possible refactoring to be spotted.

Once the method has been made static, it is clear that it can be moved out of the class, say to an unity class.

It is also easy to transform it into an instance method of one of its parameters, often this is where the code should be.


答:
There are a lot of factors.  I'll list them roughly in order:

Code Reviews.  These should be for 100% of code and should frequently include a senior developer.

Pair Programming.  One of the best (though hard) ways to write good code is do pair programming.  The challenge is finding a good pair as not all personalities pair well.

Tests.  Code code has good tests that acts as documentation on how to use functions and encourage function usage.

Working conditions that encourage discussion, notable an open environment that clusters folks together.

A culture of learning, including lunch-time stuff, books, training, etc.

A culture of software craftmanship with featured refactoring skills and demonstrations of approaches.

Tools that analyze code for quality metrics.


问:
How do I prevent unknowningly duplicating code?
I work on a rather large code base. Hundreds of classes, tons of different files, lots of functionality, takes more than 15 minutes to pull down a fresh copy, etc.

A big problem with such a large code base is that it has quite a few utility methods and such that do the same thing, or has code that doesn't use these utility methods when it could. And also the utility methods aren't just all in one class (because it'd be a huge jumbled mess).

I'm rather new to the code base, but the team lead who's been working on it for years appears to have the same problem. It leads to a lot of code and work duplication, and as such, when something breaks, it's usually broken in 4 copies of basically the same code

How can we curb this pattern? As with most large projects, not all code is documented(though some is) and not all code is... well, clean. But basically, it'd be really nice if we could work on improving the quality in this respect so that in the future we had less code duplication, and things like utility functions were easier to discover.

Also, the utility functions are usually either in some static helper class, in some non-static helper class that works on a single object, or is a static method on the class which it mainly "helps" with.

I had one experiment in adding utility functions as Extension methods(I didn't need any internals of the class, and it definitely was only required in very specific scenarios). This had the effect of preventing cluttering up the primary class and such, but it's not really anymore discoverable unless you already know about it

答:
We could also try to see the problem from another angle. Instead of thinking that the problem is the code duplication, we may consider if the problem originates in the lack of policies for code reuse.

I recently read the book Software Engineering with Reusable Components and it indeed has a set of very interesting ideas on how to foster code reusability at the organization level.

The author of this book, Johannes Sametinger, describes a set of barriers to code reuse, some conceptual some technical. For instance:

Conceptual and Technical

Difficulty finding reusable software: software cannot be reuse unless it can be found. Reuse is unlikely to happen when a repository
does not have sufficient information about components or when
components are poorly classified.

Nonreusability of found software: easy access to existing software does not necessarily increase software reuse.
Unintentionally, software is seldom written in a way so that others
can reuse it. Modifying and adapting someone else's software can
become even more expensive than programming the needed functionality
from scratch.

Legacy components not suitable for reuse: Reuse of components is hard or impossible unless they have been designed and developed for
reuse. Simply gathering existing components from various legacy
software systems and trying to reuse them for new developments is not
sufficient for systematic reuse. Re-engineering can help in extracting
reusable components, however the effort might be considerable.

Object-oriented technology: It is widely believed that object-oriented technology has a positive impact on software reuse.
Unfortunately and wrongly, many also believe reuse depends on this
technology or that adopting object-oriented technology suffices for
software reuse.

Modification: components will not always be exactly the way we want them. If modifications are necessary, we should be able to
determine their effects on the component and its previous verification
results.

Garbage reuse: Certifying reusable components to certain quality levels helps minimizing possible defects. Poor quality controls is one
of the major barriers to reuse. We need some means of judging whether
the required functions match the functions provided by a component.

Other basic technical difficulties include

Agreeing on what a reusable component constitutes.

Understanding what a component does and how to use it.

Understanding how to interface reusable components to the rest of a design.

Designing reusable components so that they are easy to adapt and modify in a controlled way.

Organizing a repository so that programmers can find and use what they need.

According to the author, different levels of reusability happen depending on the maturity of an organization.

Ad-hoc reuse among application groups: if there is no explicit commitment to reuse, then reuse can happen in an informal and
haphazard way at best. Most of the reuse, if any, will occur within
projects. This also leads to code scavenging and ends up in code
duplication.

Repository-based reuse among application groups: the situation slightly improves when a component repository is used and can be
accessed by various application groups. However, no explicit mechanism
exists for putting components into the repository and no one is
responsible for the quality of the components in the repository. This
can lead to many problems and hamper software reuse.

Centralized reuse with a component group: In this scenario a component group is explicitly responsible for the repository. The
group determines which components are to be stored in the repository
and ensures that quality of these components and the availability of
the necessary documentation, and helps retrieving suitable components
in a particular reuse scenario. Application groups are separated from
the component group, which acts as a kind of subcontractor to each
application group. An objective of the component group is to minimize
redundancy. In some models, the members of this group can also work on
specific projects. During project start-ups their knowledge is
valuable to foster reuse and thanks to their involvement in a
particular project they can identify possible candidates for inclusion
in the repository.

Domain-based Reuse: The specialization of component groups amounts to domain-based reuse. Each domain group is responsible for
components in its domain, e.g. network components, user interface
components, database components.

So, maybe, besides all the suggestions given in other answers, you could work on design a reusability program, involve management, form a component group responsible for identifying reusable components by doing domain analysis and define a repository of reusable components that other developers can easily query and look for cooked solutions to their problems.


问:
How are virtual methods slower in C#?
I read that virtual calls make the code slower than calling non-virtual ones in C#.
However, the IL instruction for both are the same callvirt except in cases where base.somemethod() is called.

So how does virtual method hurt performance?

答:
As pointed out here, calling callvirt is slower, but by a very small margin. I'm not sure how you're getting the CIL code, but as Eric Gunnerson points out, .NET never uses call for instance classes. It always uses callvirt, and he even states in a follow-up post that the difference in performance impact is minimum.

Just a very quick test, where all classes have a void PrintTest() method (which only prints a message to the console)...

BaseVirtual is a base class with the method defined as virtual.

DerivedVirtual and DerivedVirtual2 use override to redefine the virtual method, inheriting from BaseVirtual.

Base is a regular class with a regular instance method (no virtual or sealed).

Seal is a sealed class, just for the kicks.

Stat is a class with the method defined as static.

Here's the main code:

```<code>using System;

namespace CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            BaseVirtual baseVirtual = new BaseVirtual();
            DerivedVirtual derivedVirtual = new DerivedVirtual();
            DerivedVirtual2 derivedVirtual2 = new DerivedVirtual2();
            Base regularBase = new Base();
            Seal seal = new Seal();

            baseVirtual.PrintTest();
            derivedVirtual.PrintTest();
            derivedVirtual2.PrintTest();
            regularBase.PrintTest();
            seal.PrintTest();
            Stat.PrintTest();
        }
    }
}
</code>```

And, here's the CIL code:

```<code>.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       68 (0x44)
  .maxstack  1
  .locals init ([0] class CSharp.BaseVirtual baseVirtual,
           [1] class CSharp.DerivedVirtual derivedVirtual,
           [2] class CSharp.DerivedVirtual2 derivedVirtual2,
           [3] class CSharp.Base regularBase,
           [4] class CSharp.Seal seal)
  IL_0000:  newobj     instance void CSharp.BaseVirtual::.ctor()
  IL_0005:  stloc.0
  IL_0006:  newobj     instance void CSharp.DerivedVirtual::.ctor()
  IL_000b:  stloc.1
  IL_000c:  newobj     instance void CSharp.DerivedVirtual2::.ctor()
  IL_0011:  stloc.2
  IL_0012:  newobj     instance void CSharp.Base::.ctor()
  IL_0017:  stloc.3
  IL_0018:  newobj     instance void CSharp.Seal::.ctor()
  IL_001d:  stloc.s    seal
  IL_001f:  ldloc.0
  IL_0020:  callvirt   instance void CSharp.BaseVirtual::PrintTest()
  IL_0025:  ldloc.1
  IL_0026:  callvirt   instance void CSharp.BaseVirtual::PrintTest()
  IL_002b:  ldloc.2
  IL_002c:  callvirt   instance void CSharp.BaseVirtual::PrintTest()
  IL_0031:  ldloc.3
  IL_0032:  callvirt   instance void CSharp.Base::PrintTest()
  IL_0037:  ldloc.s    seal
  IL_0039:  callvirt   instance void CSharp.Seal::PrintTest()
  IL_003e:  call       void CSharp.Stat::PrintTest()
  IL_0043:  ret
} // end of method Program::Main
</code>```

Nothing too fancy, but this shows that only the static method used call.
Even so, I don't think this will really make a difference for most applications, so we shouldn't sweat on the small stuff and worry about this.

So, in conclusion, as the SO post states, you may get a performance hit because of the lookup the runtime needs to call the virtual methods. Compared to static methods, you get the overhead of callvirt.

... Well, that was fun...

Title: How are virtual methods slower in C#?

Body:
As pointed out here, calling callvirt is slower, but by a very small margin. I'm not sure how you're getting the CIL code, but as Eric Gunnerson points out, .NET never uses call for instance classes. It always uses callvirt, and he even states in a follow-up post that the difference in performance impact is minimum.

Just a very quick test, where all classes have a void PrintTest() method (which only prints a message to the console)...

BaseVirtual is a base class with the method defined as virtual.

DerivedVirtual and DerivedVirtual2 use override to redefine the virtual method, inheriting from BaseVirtual.

Base is a regular class with a regular instance method (no virtual or sealed).

Seal is a sealed class, just for the kicks.

Stat is a class with the method defined as static.

Here's the main code:

using System;

namespace CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            BaseVirtual baseVirtual = new BaseVirtual();
            DerivedVirtual derivedVirtual = new DerivedVirtual();
            DerivedVirtual2 derivedVirtual2 = new DerivedVirtual2();
            Base regularBase = new Base();
            Seal seal = new Seal();

            baseVirtual.PrintTest();
            derivedVirtual.PrintTest();
            derivedVirtual2.PrintTest();
            regularBase.PrintTest();
            seal.PrintTest();
            Stat.PrintTest();
        }
    }
}

And, here's the CIL code:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       68 (0x44)
  .maxstack  1
  .locals init ([0] class CSharp.BaseVirtual baseVirtual,
           [1] class CSharp.DerivedVirtual derivedVirtual,
           [2] class CSharp.DerivedVirtual2 derivedVirtual2,
           [3] class CSharp.Base regularBase,
           [4] class CSharp.Seal seal)
  IL_0000:  newobj     instance void CSharp.BaseVirtual::.ctor()
  IL_0005:  stloc.0
  IL_0006:  newobj     instance void CSharp.DerivedVirtual::.ctor()
  IL_000b:  stloc.1
  IL_000c:  newobj     instance void CSharp.DerivedVirtual2::.ctor()
  IL_0011:  stloc.2
  IL_0012:  newobj     instance void CSharp.Base::.ctor()
  IL_0017:  stloc.3
  IL_0018:  newobj     instance void CSharp.Seal::.ctor()
  IL_001d:  stloc.s    seal
  IL_001f:  ldloc.0
  IL_0020:  callvirt   instance void CSharp.BaseVirtual::PrintTest()
  IL_0025:  ldloc.1
  IL_0026:  callvirt   instance void CSharp.BaseVirtual::PrintTest()
  IL_002b:  ldloc.2
  IL_002c:  callvirt   instance void CSharp.BaseVirtual::PrintTest()
  IL_0031:  ldloc.3
  IL_0032:  callvirt   instance void CSharp.Base::PrintTest()
  IL_0037:  ldloc.s    seal
  IL_0039:  callvirt   instance void CSharp.Seal::PrintTest()
  IL_003e:  call       void CSharp.Stat::PrintTest()
  IL_0043:  ret
} // end of method Program::Main

Nothing too fancy, but this shows that only the static method used call.
Even so, I don't think this will really make a difference for most applications, so we shouldn't sweat on the small stuff and worry about this.

So, in conclusion, as the SO post states, you may get a performance hit because of the lookup the runtime needs to call the virtual methods. Compared to static methods, you get the overhead of callvirt.

... Well, that was fun...


问:
When to use custom collections?
I see a lot of APIs that use custom collections instead of just using strongly-typed packaged generics.

For instance, the API will have a Object1Collection instead of just a List<Object1> (or whatever the appropriate generic would be).

When do you know to use one or the other?  I understand you'd create a custom collection if you want to extend the capabilities of a pre-shipped generic collection, but what if that's not the case?

Is it prudent to create the custom collection from the beginning, with thoughts that in the future that object might scale up and require further capabilities, and it may be easier to just do that initially?  Is that justification enough?

And if you just want to extend functionality, instead of define collection functionality, you would just derive your custom collection from a base generic collection class, otherwise inherit the interface accordingly?  Is that typical?

答:
In general, rarely if ever.

You'll occasionally make things that wrap collections and work on collections of things, but you will rarely make a class that is a generic, reusable collection. More often you'll have some class that represents some concept which uses a collection, rather than is a collection.

Why? Because frankly there's only so many data structures in the world, and they've pretty much all been implemented. Maybe you can come up with the next hash table, and if you do, then make a new collection type for it.

If you want to add functionality, either wrap the existing collection or add extension methods to it.

If you see a specific ObjectCollection, I would assume that the API was made during .NET 1.0 (no generics) or for some API that has onerous interoperability requirements put in it.

Title: When to use custom collections?


问:
Smallest and Largest contiguous repeating sub-sequence in a sequence
I am trying to solve a outdated quiz problem.

I am tasked to find the smallest and largest contiguous sequence of repeating numbers in a larger sequence.
e.g.

```<code>{1,3,6,17,19,3,6,5,4,2,5,6,17,19,3,6,7,5,78,100,101}
</code>```

For the sequence above, the smallest (non-zero element sequence) and largest non extensible sub sequence would be smallest - 3,6 and largest - 6,17,19,3,6

Could not get started with an algorithm. Any help to get me started would be much appreciated.

答:
You need a data structure and a way to manipulate it.

One possibility is a tree.  Each node of the tree (except the root) contains a value equal to a number in the input sequence, but the same value may (in fact usually will) occur in multiple nodes of the tree.  Each node also contains a list of "starting points", which could just be the relative positions of the elements of the list (0 through N-1).  For any unidirectional path from the root to a node in the tree, the values stored in the nodes on the path are the numbers in a subsequence of the input sequence, and the starting points listed in the destination node are all the positions in the input sequence where a
copy of that subsequence starts.

In your example, here are just a few of the nodes that would occur in the tree:

```<code>() -> (3, (1, 5, 14)) -> (6, (1, 5, 14)) -> (5, (5))
</code>```

That is, () is the root node, one of its children is (3,(1,5,14)), and so forth.  These nodes represent the fact that there is a one-element subsequence (3) starting at positions 1, 5, and 14; the  subsequence (3,6) also starts at positions 1, 5, and 14; but the subsequence (3,6,5) occurs only at position 5.  There are many other nodes I have not shown here, for example the ones representing the fact that a subsequence (3,6,17) starts at position 1, and that (3,6,7) starts at position 14.

To make this tree represent all subsequences starting at a given position in the input sequence, you start at that position and read consecutive numbers from the input until you reach the end of the input. As you read each number you move one step down the tree to a node containing that number (if there is no such node, you create it), and you append the given starting position in the list at that node.

The tree is complete when you have done this once for each possible starting position in the list.  At that time, any repeated subsequence is represented by a node whose list contains two or more starting positions. The deepest such node tells you what the longest repeated subsequence was.

If the longest subsequence were all you needed, it would have been enough to keep a counter at each node instead of a list.  But for the shortest non-extensible subsequence, it's helpful to know those starting positions.  For example, choose any node you like in the tree.  Consider the subsequence represented by that node.  To determine that the subsequence can't be extended toward the end of the list, verify that none of the children of your chosen node has more than one starting point in its list.  To determine that the subsequence can't be extended toward the start of the list, look at the numbers in the input sequence immediately before each of your chosen node's starting points, and verify that no two of those numbers are equal.  You can do a breadth-first search of the tree and stop when you find a node that passes both of those tests.

But looking at the input again, I see that the subsequence (19,3,6) occurs twice, so perhaps I misunderstood your criteria for "shortest repeating subsequence". If what you mean is that there is at least one copy of (3,6), the one starting at position 1, that is repeated elsewhere in the input but cannot be extended forward or backward, then instead of "no two of those numbers are equal", the previous paragraph should say, "there is at least one number that occurs exactly once."  That is, in the example, the subsequence (3,6) starting at position 1 is preceded by the value 1, and that is the only time that (3,6) is preceded by 1.

This is surely not the fastest way to get an answer, but it's better than some brute-force approaches might be.  There are still plenty of implementation details to optimize.  You might be able to optimize it much further; for example, rather than using the procedure I gave for filling in the nodes of the tree, perhaps you can use a procedure of the kind outlined by david.pfx, in which case the resulting tree will be much smaller (because you don't build a lot of nodes that have no purpose).

Body:
You need a data structure and a way to manipulate it.

One possibility is a tree.  Each node of the tree (except the root) contains a value equal to a number in the input sequence, but the same value may (in fact usually will) occur in multiple nodes of the tree.  Each node also contains a list of "starting points", which could just be the relative positions of the elements of the list (0 through N-1).  For any unidirectional path from the root to a node in the tree, the values stored in the nodes on the path are the numbers in a subsequence of the input sequence, and the starting points listed in the destination node are all the positions in the input sequence where a
copy of that subsequence starts.

In your example, here are just a few of the nodes that would occur in the tree:

() -> (3, (1, 5, 14)) -> (6, (1, 5, 14)) -> (5, (5))

That is, () is the root node, one of its children is (3,(1,5,14)), and so forth.  These nodes represent the fact that there is a one-element subsequence (3) starting at positions 1, 5, and 14; the  subsequence (3,6) also starts at positions 1, 5, and 14; but the subsequence (3,6,5) occurs only at position 5.  There are many other nodes I have not shown here, for example the ones representing the fact that a subsequence (3,6,17) starts at position 1, and that (3,6,7) starts at position 14.

To make this tree represent all subsequences starting at a given position in the input sequence, you start at that position and read consecutive numbers from the input until you reach the end of the input. As you read each number you move one step down the tree to a node containing that number (if there is no such node, you create it), and you append the given starting position in the list at that node.

The tree is complete when you have done this once for each possible starting position in the list.  At that time, any repeated subsequence is represented by a node whose list contains two or more starting positions. The deepest such node tells you what the longest repeated subsequence was.

If the longest subsequence were all you needed, it would have been enough to keep a counter at each node instead of a list.  But for the shortest non-extensible subsequence, it's helpful to know those starting positions.  For example, choose any node you like in the tree.  Consider the subsequence represented by that node.  To determine that the subsequence can't be extended toward the end of the list, verify that none of the children of your chosen node has more than one starting point in its list.  To determine that the subsequence can't be extended toward the start of the list, look at the numbers in the input sequence immediately before each of your chosen node's starting points, and verify that no two of those numbers are equal.  You can do a breadth-first search of the tree and stop when you find a node that passes both of those tests.

But looking at the input again, I see that the subsequence (19,3,6) occurs twice, so perhaps I misunderstood your criteria for "shortest repeating subsequence". If what you mean is that there is at least one copy of (3,6), the one starting at position 1, that is repeated elsewhere in the input but cannot be extended forward or backward, then instead of "no two of those numbers are equal", the previous paragraph should say, "there is at least one number that occurs exactly once."  That is, in the example, the subsequence (3,6) starting at position 1 is preceded by the value 1, and that is the only time that (3,6) is preceded by 1.

This is surely not the fastest way to get an answer, but it's better than some brute-force approaches might be.  There are still plenty of implementation details to optimize.  You might be able to optimize it much further; for example, rather than using the procedure I gave for filling in the nodes of the tree, perhaps you can use a procedure of the kind outlined by david.pfx, in which case the resulting tree will be much smaller (because you don't build a lot of nodes that have no purpose).