答:
Now, I can call both swan.fly() and dove.fly(), but swan gets its implementation from FlyingBird. The idiom "Favor composition over inheritance" tells me to favor the Dove implementation over Swan, but "subtype polymorphism" doesn't seem to make that distinction.

Does subtype polymorphism distinguish between inheriting behavior, or inheriting an interface?

It doesn't. The criteria for polymorphism is substitutability of behavior. It's possible to have subtype polymorphism without classes, implementation inheritance or interfaces being involved.

As an example, consider tuples - an immutable sequence of n values of possibly different types. E.g. the type (float, float) is the type of 2-tuples whose first element is an integer and whose second element is a floating point number. The only operations tuple types have is selection - retrieving the ith element of the tuple (for i <= n). So the only things we can do with an (float, float) value is retrieve the first element or the second element (the float).

Now consider the type (float, float, string). This is a distinct type from (float, float), but we can apply the same operations to it - we can retrieve the first element and second elements, and the types match. So we could substitute an (float, float, string) anywhere a (float, float) is expected and the program would still work.

A language's type system may or may not decide to allow such substitutions. On the one hand, allowing them increases the number of valid programs in the language. On the other hand, you're weakening the conditions you can assert through the type system - now you can't enforce that if a function takes an (float, float) as an argument, it's actually receiving an (float, float) and not some 3-tuple (or 4-tuple or...) that happens to be substitutable. You could, for example, inadvertently pass a (float, float, float) representing Red/Blue/Green pixel data to a function expecting a (float, float) representing a 2D point and the program would compile.

Note, however, that the language can't force user-defined types to be substitutable. Nothing stops you from creating a Penguin implements Flyable that simply throws an exception when you call fly(). The burden of ensuring substitutability falls upon the programmer. And if you deliberately design classes that break their superclass's contracts, you will inflict much pain and misery upon yourself and others. But this is nothing new - the type system can only ensure that if an expression returns a value, it's of the correct type. Just because I write a function double squareRoot(double x) it doesn't automatically mean I'll actually return the square root of x. I should, but the compiler can't force me.

As for why you should favor composition over inheritance, that's a different question.

Body:
To provide some context, I've seen some comments lately that equate inheriting behavior from a supertype, with inheriting a pure interface with no behavior. But there are pretty significant, and different, consequences to each.

e.g. Here's a sample base class, and a "pure" interface (pseudocode):

```<code>class FlyingBird {
    void fly() {
        change state due to flight
    }
}

interface Flyable {
    void fly();
}
</code>```

Now Let's say I have Swan and Dove. I'll subclass Swan from FlyingBird, and have Dove implement Flyable.

```<code>Swan extends FlyingBird {
    (no defnition for fly, because we inherit it from FlyingBird)
}

Dove implements Flyable {
    void fly() {
        ... must provide implementation for fly, because the interface only provides the signature
    }
</code>```

Now, I can call both swan.fly() and dove.fly(), but swan gets its implementation from FlyingBird. The idiom "Favor composition over inheritance" tells me to favor the Dove implementation over Swan, with some sort of injected implementation, but "subtype polymorphism" doesn't seem to make that distinction.

The distinction is important, because, for example:

There's a growing movement in OO to make classes "final" or "non-extendable" by default, because of the complexities of inheriting behavior without breaking the super-classes' semtantics. In other words, some people are suggesting that one form of subtype prototyping should be disabled by default. (I haven't heard anyone suggest getting rid of interfaces in Java.)

"Favor composition over inheritance" differentiates sharing behavior through class inheritance vs. providing a common interface backed by a shared implementation.

In other words, there are practical and important differences between inheriting behavior and just inheriting an interface.

Does subtype polymorphism distinguish between inheriting behavior, or inheriting an interface?


问:
Types of unit tests based on usefulness
From value point of view I see two groups of unit tests in my practice:

Tests that test some non-trivial logic. Writing them (either before
implementation or after) reveals some problems/potential bugs and
helps to be confident in case logic is changed in the future.

Tests that test some very trivial logic. Those tests more like
document code (typically with mocks) than test it. The maintenance
workflow of those tests is not "some logic changed, test became red - thanks God I wrote this test" but "some trivial code changed, test became false negative - I have to maintain (rewrite) the test
without gaining any profit". Most of the time those tests are not
worth maintaining (except religious reasons). And according to my
experience in many systems those tests are like 80% of all tests.

I am trying to find out what other guys think on the topic of unit tests separation by value and how it corresponds to my separation. But what I mostly see is either fulltime TDD propaganda or tests-are-useless-just-write-the-code propaganda. I'm interested in something in the middle. Your own thoughts or references to articles/papers/books are welcome.

答:
Here's my take on it:  all tests have costs:

initial time and effort:

think about what to test and how to test it

implement the test and make sure it's testing what it's supposed to

ongoing maintenance

making sure the test is still doing what it's supposed to do as the code evolves naturally

running the test

execution time

analyzing the results

We also intend for all tests to provide benefits (and in my experience, nearly all tests do provide benefits):

specification

highlight corner cases

prevent regression

automatic verification

examples of API usage

quantification of specific properties (time, space)

So it's pretty easy to see that if you write a bunch of tests, they're probably going to have some value.  Where this gets complicated is when you start comparing that value (which, by the way, you may not know in advance -- if you throw away your code, the regression tests lose their value) to the cost.

Now, your time and effort are limited.  You would like to choose to do those things that provide the most benefit at the least cost.  And I think that is a very difficult thing to do, not least because it may require knowledge that one does not have or would be expensive to obtain.

And that's the real rub between these different approaches.  I believe they've all identified testing strategies which are beneficial.  However, each strategy has different costs and benefits in general.  Also, the costs and benefits of each strategy will probably be heavily dependent on the specifics of the project, the domain, and the team.  In other words, there may be multiple best answers.

In some cases, pumping out code without tests may provide the best benefits/costs.  In other cases, a thorough test suite may be better.  In still other cases, improving the design may be the best thing to do.

ContentLicense: CC BY-SA 3.0

Title: Types of unit tests based on usefulness


问:
Is there any performance benefit in checking the item count prior to executing a foreach loop?
I saw this in code and was wondering if there is any performance benefit to checking the item count prior to looping:

```<code>if (SqlParams.Count > 0)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

I always prefer to do a null check instead and let the foreach loop just hop out if there are 0 items.

```<code>if (SqlParams != null)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

Isn't that the better way?

答:
The only scenario I can think of where checking Count first would help performance is with a collection having a resource-hungry IEnumerable.MoveNext() implementation and yet an highly efficient ICollection.Count implementation. While it's technically possible, it's very unlikely that it would ever happen.

In fact, on some scenarios, checking Count() first would actually be less performant. Think for example of ORM frameworks like Entity Framework which takes advantage of linq's IQueryable interface. Behind the scenes, these objects reaches out to a datastore to provide collections of objects and computing operation results like sums, averages and of course count. Calling IQueryable.Count() here would actually end up making a SELECT COUNT(*) ... query on the database. If you don't need that information then it would just be needless overhead to get it.

Bottom line: I really wouldn't change anything to your actual coding style. It's perfectly acceptable to loop through a collection right away, even if it turns out to be empty. Making sure it isn't null first is okay if you cannot be sure of its provenance.


答:
I believe it is important to have tests of both types and to use them where appropriate.

Like you said, there are two extremes and I honestly do not agree with either one as well.

The key is that unit tests have to cover business rules and requirements. If there is a requirement that the system must track a person's age, write "trivial" tests to ensure the age is a nonnegative integer. You are testing the domain of data required by the system: while trivial, it has value because it is enforcing the parameters of the system.

Likewise with more complex tests, they have to bring value. Sure, you can write a test that validates something that is not a requirement but should be enforced in an ivory tower somewhere, but that is time better spent writing tests that validate the requirements for which the customer is paying you. For example, why write a test that validates your code can deal with an input stream that times out, when the only streams are from local files, not the network?

I firmly believe in unit testing and use TDD wherever it makes sense. Unit tests certainly bring value in the form of increased quality and "fail fast" behavior when changing code. However, there is the old 80/20 rule to keep in mind too. At some point you will reach diminishing returns when writing tests, and you need to move to more productive work even if there is some measurable value to be had from writing more tests.

Title: Types of unit tests based on usefulness

Body:
From value point of view I see two groups of unit tests in my practice:

Tests that test some non-trivial logic. Writing them (either before
implementation or after) reveals some problems/potential bugs and
helps to be confident in case logic is changed in the future.

Tests that test some very trivial logic. Those tests more like
document code (typically with mocks) than test it. The maintenance
workflow of those tests is not "some logic changed, test became red - thanks God I wrote this test" but "some trivial code changed, test became false negative - I have to maintain (rewrite) the test
without gaining any profit". Most of the time those tests are not
worth maintaining (except religious reasons). And according to my
experience in many systems those tests are like 80% of all tests.

I am trying to find out what other guys think on the topic of unit tests separation by value and how it corresponds to my separation. But what I mostly see is either fulltime TDD propaganda or tests-are-useless-just-write-the-code propaganda. I'm interested in something in the middle. Your own thoughts or references to articles/papers/books are welcome.


问:
Kibibtye or Kilobyte to represent 1024 bytes
I am working on a project with several older programmer and we were doing up the documentation of the program when I had a heated debate with one of the older programmers regarding the term : Kilobyte.

He wanted to stick to the old way of using Kilobytes to represent 1024 bytes as he said most programmers understood the term : Kilobyte to represent 1024 bytes.

I wanted the new way of using Kibibyte to represent 1024 bytes as we can't forever be stuck in our old ways and this has been updated by the community.

How should I resolve this conflict with him so as to appease both of us  ??

答:
Just abbreviate it to KiB, that way it's somewhat ambiguous as to whether you mean "Kilobyte" or "Kibibyte".

KiB does technically mean "Kibibyte", so, if you go with that, you may win without the other party knowing.

Realistically though, hardly anyone uses the term "Kibibyte", and it would cause more confusion to introduce it instead of using "Kilobyte".


问:
how to design a stack without using java library or using list
I have a question how to design a stack without using list or array?

This is one question that I want to think about as I want to better understand stack.

答:
A stack can either be empty (which is really easy to write), or it can not be empty in which case it has a top item and a pointer to the rest of the stack. To implement a stack without using java library,

create a class called Node, which contains a pointer reference to the
next stack entry only.

create a class called MyStack, which contains
the last stack entry. You also want to include these two functions:

push(value):

pop:


问:
Does the recent open sourcing of MSFT's C# compiler mean it can be made cross-platform?
I really enjoy working with C# however one of its biggest drawbacks is that it is kind of split-brained between MSFT .NET and Mono. In practice its not a big deal most of the time but it is one of those things that makes the language 'stink' a little. It would get a lot more uptake, I suspect, if one could answer "If I compile it, will it work on every [desktop] platform?" with "Yes.". Right now its "Yes. But you have to compile it under Mono first. And some areas of code may need to be rewritten a little.".

My question is "Does the recent open sourcing of MSFT's C# compiler mean it can be made cross-platform?". That is to say, could C# .NET be made to work cross platform without Mono with the newly release open source components? Or is there more to this I am not seeing?

Further exposition on what the future may hold for C# in light of the open sourced components is not required to answer this question however it is encouraged.

答:
It would get a lot more uptake, I suspect, if one could answer "If I compile it, will it work on every [desktop] platform?" with "Yes.".

You can say that today! (or at least you could 8 years ago when I tried)

Seriously. Build some plain jane vanilla C# (really, any .NET language) dll on windows. Good. Now move that over to some linux machine with mono. Guess what? It just works. No recompile, no cross compilation.

The entire point of using a common interface language (bytecode) for the runtime is so that you can do this very thing! Mono didn't somehow make their own bytecode for the language, they're just another implementation of the runtime.


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

答:
You could send notice of pending legal action. If that doesn't make him pay, you would have to follow through and hire a lawyer. You could try debt collection or putting a lien on his business as well, but those might be difficult absent a contract.

If your friend was unable to appeal to him, they might know members of his family that you could contact to see if they could persuade him to pay.

To prevent this from happening again in the future, I'd suggest the following:

Always use a contract, even for close friends or family members.

Require a deposit (usually 50% up
front).

Set the finished website up on
your test server so that they can use it live and suggest any changes.
Once they approve of everything,
send them a final invoice. Once the
remainder of the money has been
received, transfer everything to
their server.

Title: How to get money from reluctant client?

ContentLicense: CC BY-SA 2.5


问:
Empty virtual method on base class VS abstract methods
I couldn't find a question that was not too specific to some case, so I'll try to make this very generic.

We need an extractor base class to a set of documents, for example. Each document has its specific properties, but they're ultimately documents. So we want to provide common extraction operations for all of them.

Even though they're all documents, as I said, they're somewhat different. Some may have some properties, but some may not.

Let's imagine that we have the Document base abstract class, and the FancyDocument and NotSoFancyDocument classes that inherit from it.
The FancyDocument has a SectionA, the NotSoFancyDocument doesn't.

That said, what would you defend as the best way of implementing this? Here's the two options:

Empty virtual methods on the base class

Empty virtual methods on the base class would allow the programmer to only override the methods that make sense for the different types of documents. We would then have a default behavior on the abstract base class, which would be returning the default for the methods, like this:

```<code>public abstract class Document
{
    public virtual SectionA GetDocumentSectionA()
    {
        return default(SectionA);
    }
}

public class FancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        // Specific implementation
    }
}

public class NotSoFancyDocument : Document
{
    // Does not implement method GetDocumentSectionA because it doesn't have a SectionA
}
</code>```

Concrete empty methods or concrete methods throwing a NotImplementedException

Since the NotSoFancyDocument does not have a SectionA, but the others do, we could either just return the default for the method in it, or we could throw a NotImplementedException. That would depend on how the program was written and some other things. We could come up with something like this:

```<code>//// Return the default value

public abstract class Document
{
    public abstract SectionA GetDocumentSectionA();
}

public class FancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        // Specific implementation
    }
}

public class NotSoFancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        return default(SectionA);
    }
}
</code>```

OR

```<code>//// Throw an exception

public abstract class Document
{
    public abstract SectionA GetDocumentSectionA();
}

public class FancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        // Specific implementation
    }
}

public class NotSoFancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        throw new NotImplementedException("NotSoFancyDocument does not have a section A");
    }
}
</code>```

Personally, I do think that the abstract method approach is better, since it means "Hey, I need you to be able to get a SectionA to be a document. I don't care how." while the virtual method means "Hey, I do have this SectionA here. If it's not good enough for you, feel free to change the way I get it.".

I do think the first one is a sign of object oriented programming smell.

What are your opinions on this?

答:
I agree completely with Chao's answer and so I will not repeat that.

I think that the real problem here is that you need to ask yourself some more fundamental questions about the problem domain.  Remember that all code is written to solve a problem.

Why are we writing a base Documentclass in the first place?

Why are we deriving from the Document class?

What do we hope to gain from deriving that we would not get by a mere interface?

In this case, it seems that there are two basic needs.  There is the need to share code between document types and there is a need to get SectionA from FancyDocuments.

There is a number of ways to solve this problem and you have picked two of them.  An alternative approach that you have not considered is to use composition instead of inheritance.  In a lot of cases problems with inheritance are the result of it being the wrong tool for the job.

Consider the following as an alternative option:

```<code>sealed class Document
{
    // some stuff
}

class Fancy
{
    public Document Document { get; set; }
    public SectionA GetDocumentSectionA();
    // other fancy methods.
}

class NotFancy
{
    public Document Document { get; set; }
    // other non-fancy methods.
}
</code>```

Now you can see that the delineation between the document types is much clearer.  This disadvantage of this approach is that you cannot store both classes in the same strongly-typed Document container.  If that is important for you, then you could consider using an interface or you could use inheritance instead.

Body:
I agree completely with Chao's answer and so I will not repeat that.

I think that the real problem here is that you need to ask yourself some more fundamental questions about the problem domain.  Remember that all code is written to solve a problem.

Why are we writing a base Documentclass in the first place?

Why are we deriving from the Document class?

What do we hope to gain from deriving that we would not get by a mere interface?

In this case, it seems that there are two basic needs.  There is the need to share code between document types and there is a need to get SectionA from FancyDocuments.

There is a number of ways to solve this problem and you have picked two of them.  An alternative approach that you have not considered is to use composition instead of inheritance.  In a lot of cases problems with inheritance are the result of it being the wrong tool for the job.

Consider the following as an alternative option:

sealed class Document
{
    // some stuff
}

class Fancy
{
    public Document Document { get; set; }
    public SectionA GetDocumentSectionA();
    // other fancy methods.
}

class NotFancy
{
    public Document Document { get; set; }
    // other non-fancy methods.
}

Now you can see that the delineation between the document types is much clearer.  This disadvantage of this approach is that you cannot store both classes in the same strongly-typed Document container.  If that is important for you, then you could consider using an interface or you could use inheritance instead.


问:
How can I approach creating an efficient algorithm for maximizing value with these specific constraints?
I'm having trouble coming up with an approach that isn't n^2 for this problem. Here's a contrived, simplified version I've come up with:

Let's say you're a company that needs 4 employees to launch in a new city, a manager, two salespeople, and a customer support rep, and you magically know how much impact every candidate will have and how much salary they require to take the job. Your table of potential employees looks something like this:

```<code>Name           Position       Salary     Impact
Adam Smith     Manager        60,000     11
Allison Brown  Salesperson    40,000     9
Brad Stewart   Manager        55,000     9
...etc (thousands of records)
</code>```

What algorithmic approach can be taken to find the maximum "impact" while still filling all the positions and remaining under, say, a 200,000 budget?

Thanks!

答:
Ultimately you're going to need to write a "cost" function, and then use some algebraic technique to find the maximum(s).

If you wanted a quick-and-somewhat-dirty answer, you could use a Genetic Algorithm to propose, test, and incrementally improve answers until you got a good one. But it wouldn't be guaranteed to be the best. However, it could provide relatively quick turn-around if you wanted to tweak the formula and search again.


问:
Best practices for caching search queries
I am trying to improve performance of my ASP.net Web Api by adding a data cache but I am not sure how exactly to go about it as it seems to be more complex than most caching scenarios. An example is I have a table of Locations and an api to retrieve locations via search, for an autocomplete.

```<code>/api/location/Londo
</code>```

and the query would be something like

```<code>SELECT * FROM Locations WHERE Name like 'Londo%'
</code>```

These locations change very infrequently so I would like to cache them to prevent trips to the database for no real reason and improve the response time.

Looking at caching options I am using the Windows Azure Appfabric system, the problem is it's just a key/value cache. Since I can only retrieve items based on keys I couldn't actually use it for this scenario as far as Im aware.

Is what I am trying to do bad use of a caching system? Should I try looking into NoSql DB which could possibly run as a cache for something like this to improve performance? Should I just cache the entire table/collection in a single key with a specific data structure which could assist with the searching and then do the search upon retrieval of the data?

答:
If you're building the SQL statement as a string, you can take a hash of that and use it as a key in a distributed cache.

Depending on how many variations there are and how much memory you have, you might want to include a "time to live" or a "least used algorithm" to keep the amount of memory within limits.

However @GrandmasterB is right -- most databases do really aggressive caching of query results, so you might end up duplicating caching that's already happening. The only improvement that comes to mind is if you cache the results locally in RAM (with a least-recently-used algorithm) to save a round trip to the database.

But, no, in general that's not a bad use of caching. The caveats are that you might be duplicating caching that's already happening. Also, if the query results change a lot, then you have the usual problems with data duplication -- the cached answer getting out of sync with the "real" answer.


问:
Return multiple columns with SQL where GroupBy is on one column
I have noticed that all the columns in a SQL Select Query should be in a aggregate function, because otherwise the output value for group would be arbitrary.

This makes sense. But when the other columns are same in value, it doesn't matter which is returned. Is there a way to specify this or just use MAX() or MIN() on varchar columns?

答:
If you don't want to aggregate one or more columns that need to be displayed, include them in the column list of your query and the columns to group by list too.

```<code>SELECT Col1, Col2, SUM(Col3) AS Col3Total
FROM Table
GROUP BY Col1, Col2
ORDER BY Col1, Col2;
</code>```

In the above example, data from Col3 is summed using the combined data of Col1 and Col2 to determine where the aggregation is segregated. In other words, when the value of either Col1 or Col2 changes, a new bucket for a running sum of Col3 is created. You output data could look like this:

```
Col1  Col2  Col3Total
====  ====  =========
A     A     4
A     B     97
B     A     1
B     B     <em>NULL - assumes a NULL value was found in the Col3 data</em>
B     C     2
```

If you want to assume that Col2 has a single matching value per distinct Col1, it would like something like this:

```
Col1  Col2  Col3Total
====  ====  =========
A     Y     101
B     Z     <em>NULL - assumes a NULL value was found in the Col3 data</em>
```

Microsoft TSQL SUM function

Oracle SQL Aggregate functions

MySQL SQL Aggregate functions

Body:
If you don't want to aggregate one or more columns that need to be displayed, include them in the column list of your query and the columns to group by list too.

SELECT Col1, Col2, SUM(Col3) AS Col3Total
FROM Table
GROUP BY Col1, Col2
ORDER BY Col1, Col2;

In the above example, data from Col3 is summed using the combined data of Col1 and Col2 to determine where the aggregation is segregated. In other words, when the value of either Col1 or Col2 changes, a new bucket for a running sum of Col3 is created. You output data could look like this:

Col1  Col2  Col3Total
====  ====  =========
A     A     4
A     B     97
B     A     1
B     B     NULL - assumes a NULL value was found in the Col3 data
B     C     2

If you want to assume that Col2 has a single matching value per distinct Col1, it would like something like this:

Col1  Col2  Col3Total
====  ====  =========
A     Y     101
B     Z     NULL - assumes a NULL value was found in the Col3 data

Microsoft TSQL SUM function

Oracle SQL Aggregate functions

MySQL SQL Aggregate functions


问:
How can I make my logging more useful?
I tend to find that after I build an application, the logs emitted by it become near useless and completely unparseable, and has the problem of being really verbose, while not outputting important stuff. Example:

```<code>    Apr  9 21:49:58.648 [    DEBUG] - Read configuration successfully
    Apr  9 21:49:58.649 [     INFO] - Kirisurf started
    [{nqzosnpdzvgr5umswrnmidd3n56zipl3 54.238.54.12:2380 200 [1 2 3] true} {wq7q5idgpkopb5vbh4qmhpne42so4uue 129.97.134.129:12345 200 [0 2 3] true} {3szie5c2keiqpubsktanxlf6$
    xifwi76 203.178.133.11:12345 200 [1 0 3] true} {wmxp2o6q2z5rm5rwprnry33lbwt4ikrn 133.68.253.242:12345 200 [0 1 2] true}]
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    ALERT] - Freshened!
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    DEBUG] - Into buildings sc
    Wtfwtf
    Wtfwtf
    Wtfwtf
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    DEBUG] - Into buildings sc
    Wtfwtf
    Wtfwtf
    Apr  9 21:49:58.985 [    DEBUG] - [{wmxp2o6q2z5rm5rwprnry33lbwt4ikrn 133.68.253.242:12345 200 [0 1 2] true} {wq7q5idgpkopb5vbh4qmhpne42so4uue 129.97.134.129:12345 200 [0
    2 3] true} {nqzosnpdzvgr5umswrnmidd3n56zipl3 54.238.54.12:2380 200 [1 2 3] true}]
    Wtfwtf
    Apr  9 21:49:58.985 [    DEBUG] - Into buildings sc
    Wtfwtf
    Wtfwtf
</code>```

For example, nobody will ever know what Wtfwtf means. In fact, it was just a debug printf statement I threw in to see whether a certain part of the code got stuck. The huge strings of public keys don't have descriptions of what they are. In fact, they are dumps of a circuit state datastructure. Nobody will ever know what the references to freshness are. Nobody will ever know that sc stands for "subcircuit", which is a jargon term nobody except me uses.

However, I really can't think of any way to clean this up. I could of course use more specific terminology and remove the wtfwtf, but looking at the logging output still doesn't tell you anything about what the program is doing (namely, finding a path in a graph of network nodes, and establishing a route through them).

I also have the problem of debugging. If I remove these ugly logging statements things may become difficult to debug. What's the tradeoff? Of course I use the debug logging level, but I don't want to pollute it so much that it becomes useless for debugging, filling with junk from known not buggy code.

答:
The problem with logs is developers use logs to help them debug software rather than those using the software. They add messages that make only sense to them and remove the messages when they are not needed. This is poor practice.

Log entries like "Wtfwtf" only help a developer that can search for that string in the code. A better solution is to log something that makes sense to an operator or customer. That helps both the developer and the operator or customer.

In your case, I would:

Log information when it makes sense to a customer or operator, not developer. If the developer wants to log debug information, that's fine but strip it out in production, turn it off by default (by a logging level) or clearly differentiate it from other messages.

Provide lots of information. Having an error when user does operation X on Y? Include the user name, details of Y, the date, etc. Most systems log too little information rather than too much.

Do not log security sensitive or privacy sensitive information, like passwords or encryption keys. Be careful of logging stack traces or things that show the internal layout of code, too.

Log all errors, even if they seem unimportant, and what the system did (retried, aborted, different behaviour).

Do not log performance information or other things a log is not suited for. On Windows, for example, use Windows performance counters instead.

Use a consistent log entry format. For example, you may want to import logs into a database to provide some metrics for management or quickly search across multiple log files for information. Ensure each log entry has the same structure, dates and times have the same format and any enumerated values have defined and consistently used values. In your case, ensure any "ugly" debugging messages are at least written in the correct format.

Log using UTC dates and times. Daylight saving changes are common causes of issues. It also helps being able to correlate issues from different servers or log files easily.

Consider log retention/archiving/disposal. Log files can grow very quickly, consuming space and making them hard to search through. For example, create a new file each day and delete files older than a month. If a new log file is created when the program is run, give it a unique name so logs from older runs are not overwritten.

If logs have different audiences, log them to different locations. For example, log security sensitive information (audit information) separately. It is often needed for compliance and should not be tampered with.

Logs are rarely localized to different languages but logs may need to contain strings containing different character sets. Use a suitable encoding (e.g. UTF-8) consistently.

One easy way to address many of these is consider a logging framework like log4J or log4net. These provide a structured format, allow the log to be written to different or multiple locations (e.g. a database) and often use a separate thread pool to prevent logging becoming a bottleneck. It will also protect you from CRLF injection where someone may accidentally or maliciously try to manipulate log entries.

If the software is used internally, your organization may have logging or monitoring standards that cover some of this, particularly the log format and retention.

Regarding working out what to log, what are the steps in the algorithm? Subdivide the algorithm into steps and log the result of each one. Pretend you are the program explaining to a human how you came up with your results. It's like showing your working when doing a mathematics problem at school. Start with the high level steps then work deeper.

In your case, you describe the application it as "finding a path in a graph of network nodes and establishing a route through them". It sounds like there are two stages: finding the path then establishing it. Log those. Next, what is involved in finding a path? Sounds like an enumeration of a directed graph. Are there any optimizations that can exclude parts of the graph or recommend others? Include any details on them. As for creating a path, log the details of each device, whether the connections were successfully created and so on.

Title: How can I make my logging more useful?


问:
How do I explain to non-programers what .NET is?
I don't work at a software company, and I'm one of a small handful of people in the company that know anything about programming. I spend a lot of time automating other programs that are used in the office through public APIs, and I've also created a few stand alone applications. I work almost entirely in C#.NET as every application we seem to use in the office seems to have some form of .NET API.

I've had a few people here ask me about learning "how to program", and where they should start. I think it makes a lot more sense to learn a .NET language as nearly all the programs they would want to automate have a .NET API, and it sounds like VBA is on it's way out and being replaced by VSTA.

However, I'm trying to figure out how to explain what .NET is and why they should learn it to a someone that doesn't know anything about programming. It's not really a language, as there are a number of languages that are considered .NET languages. Plus I think there is a distinction between ".NET" and "The .NET framework" as the latter is more about the libraries provided by Microsoft.

答: I think you're heading down the right path, you have the .Net compilers that translate a program in a specific language into MSIL, then you have the Code library, which is really just a class/code library to make our life easier.  If they don't understand what a code library is, not sure what you could do to make them understand that.  You can guide them in their selection of C# the same as you did in your question.</p>


答:
Usually it is said that logging is for operators of your software. However, this is not entirely true, since DEBUG logs are usually turned on while developing, for the benefit of the developers.

I tend to regard the different levels as interesting to different roles:

DEBUG: developers only

INFO: operators / developers

WARNING: operators

ERROR/CRITICAL: users

"Developers" are people with access to the source code; "operators" are people with access to the configuration and all system interfaces (the user interface and possibly an administrative interface); and "users" are people who just have access to one interface, namely the intended user's interface.

That means, when an error happens, a developer can restart the application with an entirely different code; an operator can restart it with just a different configuration; and a user can just retry with a different input.

Just like, in an exception, you should put enough information to let client code recover from the exceptional situation, in a log statement you should put enough information to let the person reading it change whatever he/she can change on the system, in order to accomplish whatever was his/her intention.

So, if it is a DEBUG statement, state which variables or methods did not satisfy which condition, if it is a WARNING, state which part of the system is non-responsive and has to be restarted or reconfigured, and if it is an ERROR, state what input was wrong and why it could not be processed.

Remember you can't possibly know what must be done (that is why operators exist), but also remember that at the point of logging you have all informations on what is going wrong.

Just my two cents.

Title: How can I make my logging more useful?

Body:
I tend to find that after I build an application, the logs emitted by it become near useless and completely unparseable, and has the problem of being really verbose, while not outputting important stuff. Example:

```<code>    Apr  9 21:49:58.648 [    DEBUG] - Read configuration successfully
    Apr  9 21:49:58.649 [     INFO] - Kirisurf started
    [{nqzosnpdzvgr5umswrnmidd3n56zipl3 54.238.54.12:2380 200 [1 2 3] true} {wq7q5idgpkopb5vbh4qmhpne42so4uue 129.97.134.129:12345 200 [0 2 3] true} {3szie5c2keiqpubsktanxlf6$
    xifwi76 203.178.133.11:12345 200 [1 0 3] true} {wmxp2o6q2z5rm5rwprnry33lbwt4ikrn 133.68.253.242:12345 200 [0 1 2] true}]
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    ALERT] - Freshened!
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    DEBUG] - Into buildings sc
    Wtfwtf
    Wtfwtf
    Wtfwtf
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    ALERT] - Enfreshen!
    Apr  9 21:49:58.985 [    DEBUG] - Into buildings sc
    Wtfwtf
    Wtfwtf
    Apr  9 21:49:58.985 [    DEBUG] - [{wmxp2o6q2z5rm5rwprnry33lbwt4ikrn 133.68.253.242:12345 200 [0 1 2] true} {wq7q5idgpkopb5vbh4qmhpne42so4uue 129.97.134.129:12345 200 [0
    2 3] true} {nqzosnpdzvgr5umswrnmidd3n56zipl3 54.238.54.12:2380 200 [1 2 3] true}]
    Wtfwtf
    Apr  9 21:49:58.985 [    DEBUG] - Into buildings sc
    Wtfwtf
    Wtfwtf
</code>```

For example, nobody will ever know what Wtfwtf means. In fact, it was just a debug printf statement I threw in to see whether a certain part of the code got stuck. The huge strings of public keys don't have descriptions of what they are. In fact, they are dumps of a circuit state datastructure. Nobody will ever know what the references to freshness are. Nobody will ever know that sc stands for "subcircuit", which is a jargon term nobody except me uses.

However, I really can't think of any way to clean this up. I could of course use more specific terminology and remove the wtfwtf, but looking at the logging output still doesn't tell you anything about what the program is doing (namely, finding a path in a graph of network nodes, and establishing a route through them).

I also have the problem of debugging. If I remove these ugly logging statements things may become difficult to debug. What's the tradeoff? Of course I use the debug logging level, but I don't want to pollute it so much that it becomes useless for debugging, filling with junk from known not buggy code.


问:
Wrapper around C++ STL
Where I work we have our own system library, which pretty much is only wrappers around the STL, such as:

```<code>template <typename T>
class HVector {
protected:
    std::vector<T> data;
public:
    int size () const; //Only returns data.size()
    int custom(); //Some generic custom function that uses the data vector
}
</code>```

Most of the class members are just re-declarations of the STL container members, but we also have a few customized functions that do some generic tasks with the container.

Is this a good design? If not, what would be the best way to implement the customized functions around the containers?

答:
Your wrapper may have some logic inside to deal with the template. And basically all STLs are templates by themselves.

This doesn't shock me. Imagine you want to have an array of objects "Cars" and other of objects "Bicycles". Same structure but different data manipulation.

Title: Wrapper around C++ STL


问:
DDD - Domain Driven Design, which development order should be applied?
1 - Design my entities, ie (in python):

```<code>class Account:
    def __init__(name, author):
        self.name = name
        self.email = email
</code>```

2 - Design my repositories: (as interface)

```<code>class AccountRepository:
    def add(self, account):
        """ @type account Account """
        pass

    def find_by_name(self, name):
        pass

    def find_by_email(self, email):
        pass

    # remove, and others...
</code>```

Now, I can go two ways:

A: Design and implement my domain services:

```<code>class SignUpService:
    def __init__(self, account_repository):
        """ @type account_repository AccountRepository """
        self._account_repository = account_repository

    def create_account(self, username, email):
        account = Account(username, email)
        self._account_repository.add(account)

    # other methods that uses the account_repository
</code>```

B: Implement my Repositories Strategies:

```<code>class MongodbAccountRepository(AccountRepository):
    def __init__(self, mongodb_database):
        self._mongodb_database = mongodb_database

    def add(self, account):
        account_data = account.__dict__
        self._mongodb_database.accounts.insert(account_data)

    # and the other methods
</code>```

Which is the correct order? and why? 1, 2, A, B or 1, 2, B, A?

Thank you so much!

答:
Firstly I'd start off with the UI, thinking about the tasks/commands users need to perform and the data involved in each task/command. This is known as a Task-Based UI approach.

These tasks will form a 1-1 mapping with methods provided by the Application Services (different to a Domain Service).

Then I'd design my aggregates based on these tasks & data - an optimal design would be for one task/transaction (Application Service call) only involving one aggregate. To me, this is what designing aggregates based on behavior is all about.

I only implement Domain Services where a transaction needs to change state on more than one aggregate. These Domain Services abstract any logic away from the Application Service (who's job is only to orchestrate).

Storage would come last - you can only implement storage once you know exactly what you're storing?

So my full order is:

UI

Application Service (I call it a command service)

Domain

Aggregates

Domain Service

Storage

FYI I tend to follow the principals of CQRS so querying is also another 'layer' I need to consider, but I've just given the order in terms of DDD and designing aggregates.

On the subject of designing aggregates, I recommend the these articles by Vaughn Vernon

I also wrote a blog regarding designing aggregates based on behavior.


答: Just tell them it is a program that lets you write programs and not to worry about it for the moment.  Then start on the programming principles that matter the most at the moment.</p>

Title: How do I explain to non-programers what .NET is?

Body:
I don't work at a software company, and I'm one of a small handful of people in the company that know anything about programming. I spend a lot of time automating other programs that are used in the office through public APIs, and I've also created a few stand alone applications. I work almost entirely in C#.NET as every application we seem to use in the office seems to have some form of .NET API.

I've had a few people here ask me about learning "how to program", and where they should start. I think it makes a lot more sense to learn a .NET language as nearly all the programs they would want to automate have a .NET API, and it sounds like VBA is on it's way out and being replaced by VSTA.

However, I'm trying to figure out how to explain what .NET is and why they should learn it to a someone that doesn't know anything about programming. It's not really a language, as there are a number of languages that are considered .NET languages. Plus I think there is a distinction between ".NET" and "The .NET framework" as the latter is more about the libraries provided by Microsoft.


问:
Storing a C# dictionary of type <datetime,enum>
As title says it, i'm looking for a way to store many dictionaries (one per user) of type Dictionary<DateTime,enum> in a database (sql server 2012).

Each dictionary has 366 items inside and it represents a calendar where each day has a certain "status", and preferably i don't want to store each item as a separate record in the DB.
Ideas?

update:

With the suggestion @AndyBursh & @Konrad Morawski made, i've also come up with another optimisation.
Rather than by default creating a new calendar (represented as Dictionary) for each item the user adds, let them pick a predefined one from a drop down, and if that doesn't work for them, then create a separate calendar. With the ability to reuse a calendar and not storing default values, i would have to deal with a lot less data in the long term.

答:
Squashing the entire dictionary into one row doesn't really feel right, one of the basic principles of database design is atomicity.

You'd have to serialize it somehow (eg. to Json or even a blob), but this is not a recommendable solution and you won't be able to query the data conveniently.

I see no benefits of the your approach you're trying to take.

my only reason is because i will always need to get the whole list of
  items and not each record separately, also each user can have up to
  thousand of those dictionaries, and a thousand users * ~5 dictionareis
  * 366 records each = 1 830 000 records in no time

Okay, but so what? The sheer amount of data will stay the same, PLUS the overhead of deserialization ("unpacking" your dictonaries) or the inconvenience of having to deal with unusual table design (such as 366 columns).

If you're trying to cut down on the amount of data, consider other options, eg. is one enum value default / more prevalent than the others? If so, I'd only store the "unusual" values in the database and the absence of an entry would be treated as default value for the given user and day. But more context should be given.


答:
Seriously, the best way is 4 columns:

```<code>UserID (Guid or int)
CalendarNumber (smallint)
DayNumber (smallint)
Status (tinyint)
</code>```

Don't make it more complicated than it needs to be.  If you did something like create a table with 366 columns, you'll just kick yourself later when you decide that you actually want to store one extra thing for each day, or you want the Status to be a different data type.  Try not to design yourself into any corners.

Title: Storing a C# dictionary of type <datetime,enum>

Body:
As title says it, i'm looking for a way to store many dictionaries (one per user) of type Dictionary<DateTime,enum> in a database (sql server 2012).

Each dictionary has 366 items inside and it represents a calendar where each day has a certain "status", and preferably i don't want to store each item as a separate record in the DB.
Ideas?

update:

With the suggestion @AndyBursh & @Konrad Morawski made, i've also come up with another optimisation.
Rather than by default creating a new calendar (represented as Dictionary) for each item the user adds, let them pick a predefined one from a drop down, and if that doesn't work for them, then create a separate calendar. With the ability to reuse a calendar and not storing default values, i would have to deal with a lot less data in the long term.

Body:
Seriously, the best way is 4 columns:

UserID (Guid or int)
CalendarNumber (smallint)
DayNumber (smallint)
Status (tinyint)

Don't make it more complicated than it needs to be.  If you did something like create a table with 366 columns, you'll just kick yourself later when you decide that you actually want to store one extra thing for each day, or you want the Status to be a different data type.  Try not to design yourself into any corners.


答:
Whilst a database would be great at storing a huge number of (user, datetime, enum)  tuples, there is another approach that could be taken.

Let's assume that the majority of datetime values would have a default enum value DEFAULT. Instead of storing all (#users)*366 records, one could store just those records which have an enum value which is not DEFAULT. Handling this in code would be as simple as initialising the full range of datetime values with the DEFAULT enum value, then fetching the records from the database and replacing the enum values of the fetched datetimes.

```<code>Dictionary<DateTime, MyEnum> GetDictionary(int UserId)
{
    DateTime startDate = new DateTime();
    Dictionary<DateTime, MyEnum> calendar =
        (from i in Enumerable.Range(0, 365)
        let dt = startDate.AddDays(i);
        select { date = dt, enumVal = MyEnum.DEFAULT})
        .ToDictionary(k => k.date, v => v.enumVal);

    var rows = this.FetchRows(UserId);
    foreach(SomeRow R in rows)
    {
        calendar[R.datetime] = R.enumValue;
    }
    return calendar;
}
</code>```

Body:
Whilst a database would be great at storing a huge number of (user, datetime, enum)  tuples, there is another approach that could be taken.

Let's assume that the majority of datetime values would have a default enum value DEFAULT. Instead of storing all (#users)*366 records, one could store just those records which have an enum value which is not DEFAULT. Handling this in code would be as simple as initialising the full range of datetime values with the DEFAULT enum value, then fetching the records from the database and replacing the enum values of the fetched datetimes.

Dictionary<DateTime, MyEnum> GetDictionary(int UserId)
{
    DateTime startDate = new DateTime();
    Dictionary<DateTime, MyEnum> calendar =
        (from i in Enumerable.Range(0, 365)
        let dt = startDate.AddDays(i);
        select { date = dt, enumVal = MyEnum.DEFAULT})
        .ToDictionary(k => k.date, v => v.enumVal);

    var rows = this.FetchRows(UserId);
    foreach(SomeRow R in rows)
    {
        calendar[R.datetime] = R.enumValue;
    }
    return calendar;
}


问:
Empty superclass for Collection of derived classes
Basically, what I would like to obtain is a way to iterate through ONE list, and call methods specific to the interface the objects in the collection implement.

In my Java project, it would result in something like this:

```<code>//GameComponent would be my empty abstract class
HashSet<GameComponent> components = new HashSet<GameComponent>();
components.add(/* instance of a class that extends GameComponent and implements Drawable || Updatable */);

for (Drawable d : components)
    d.draw();

for (Updatable u : components)
    u.update();
</code>```

My friends suggested me to just make two separate lists, but that means some objects will be in both lists.

I also think that it makes sense (abstraction-wise) to have one list of GameComponents and iterate through that one list.

But I also don't like having an empty class to inherit from, only for categorisation.

So, the question is: does my approach make sense? If so, is it elegant? If not, what pattern could I follow?

答:
A few things to consider:

Why is GameComponent empty? If there are any methods/properties that are shared between all children of GameComponent it wouldn't have to be an empty abstract base class.

Does GameComponent have to be a class? If you're not defining any default behaviour or values in it, you could just as well make it an interface.

An empty interface is not neater/more elegant per se, but using interfaces to 'tag' an object as being of a certain type let's it keep its ability to extend another class.


问:
Does agile approach support taking a task from a team?
Can customer take one of tasks during the planning meeting, which was already assigned to this team, and put it to another team? For example because a customer think that the other team will be faster in implementing it?
Is it normal for some agile methodologies? If yes, could you, please, provide me with the source of this information(book or web link), because I do not know how to handle it, especially because of team spirit: such a thing can make people in team demotivated and also there can origin some tenses in between these two teams...

It is part of some agile methodology and what are the constraints to make this thing?

答:
Why do you let customers dictate how work gets done? How would they even know about the speed of your teams?

To answer your question: no. The team self organises and chooses how to distribute the work. If the customer has some hard deadline in mind, he/she should communicate that deadline and trust the team or teams to meet that deadline. How the teams achieve that is not the concern of the customer.


答:
This is what I'm doing in my latest project -- for the first time, so haven't totally tested in production.

```<code>#9384752 --- Jan 4, 2014 4:58:16 >>> FAILED :: [Chart] render <<< chart.class.php @ 43
</code>```

And it parses like:

#9384752 Unique identifier in order to find/mark each separated line easier.

--- A very visible and eye-friendly separator.

Jan 4, 2014 4:58:16 Human readable date/time

>>> A very visible and eye-friendly separator.

FAILED Record status.

:: Again, separator.

[Chart] Module name.

render The actual log message.

<<< Separator.

chart.class.php File name.

@ Separator.

43 Line number.

The idea is to have a useful Debug logs -- in the above example, so I tried to make it readable as much as possible. Those ---, >>> and <<<, they all help me read the log easier. Also it is easier to Search between logs -- e.g. >>> FAILED :: is unique within the entire record, so can be a keyword for jumping between records with no need to skip between similar words in the log messages itself. Parsing log records with Regular Expressions or string functions is much easier as well.

Also the Record Identifier helps me address that specific record later or when assigning tasks to other developers.

The Log Message itself is quite short as I hate to get lost between tons of words and have to read them to understand what's going on. In the above example I can simply understand that:

render method of Chart module, located in chart.class.php has failed at line 43.

Literally in a second.

So the key points are:

Make it usable

Make it readable and eye-friendly

Make it search-friendly

Address the problem, as short as possible, but include the necessary information

Locate where does did the error happen

P.S. As I said this is the first time I'm using this format in a project, so there are potentially design-flaws that I'm not aware of.

P.P.S. This is my developer-friendly debug logs, so someone might not find it very suitable for other logging purposes.

Title: How can I make my logging more useful?

Body:
This is what I'm doing in my latest project -- for the first time, so haven't totally tested in production.

#9384752 --- Jan 4, 2014 4:58:16 >>> FAILED :: [Chart] render <<< chart.class.php @ 43

And it parses like:

#9384752 Unique identifier in order to find/mark each separated line easier.

--- A very visible and eye-friendly separator.

Jan 4, 2014 4:58:16 Human readable date/time

>>> A very visible and eye-friendly separator.

FAILED Record status.

:: Again, separator.

[Chart] Module name.

render The actual log message.

<<< Separator.

chart.class.php File name.

@ Separator.

43 Line number.

The idea is to have a useful Debug logs -- in the above example, so I tried to make it readable as much as possible. Those ---, >>> and <<<, they all help me read the log easier. Also it is easier to Search between logs -- e.g. >>> FAILED :: is unique within the entire record, so can be a keyword for jumping between records with no need to skip between similar words in the log messages itself. Parsing log records with Regular Expressions or string functions is much easier as well.

Also the Record Identifier helps me address that specific record later or when assigning tasks to other developers.

The Log Message itself is quite short as I hate to get lost between tons of words and have to read them to understand what's going on. In the above example I can simply understand that:

render method of Chart module, located in chart.class.php has failed at line 43.

Literally in a second.

So the key points are:

Make it usable

Make it readable and eye-friendly

Make it search-friendly

Address the problem, as short as possible, but include the necessary information

Locate where does did the error happen

P.S. As I said this is the first time I'm using this format in a project, so there are potentially design-flaws that I'm not aware of.

P.P.S. This is my developer-friendly debug logs, so someone might not find it very suitable for other logging purposes.


问:
What is the difference between self-types and trait inheritance in Scala?
When Googled, many responses for this topic come up. However, I don't feel like any of them do a good job of illustrating the difference between these two features. So I'd like to try one more time, specifically...

What is something that can be done with self-types and not with inheritance, and vice-versa?

To me, there should be some quantifiable, physical difference between the two, otherwise they are just nominally different.

If Trait A extends B or self-types B, don't they both illustrate that being of B is a requirement? Where is the difference?

答:
I have some code that illustrates some of the differences wrt visibility and "default" implementations when extending vs setting a self-type. It does not illustrate any of the parts discussed already about how actual name collisions are resolved, but instead focuses on what is possible and not possible to do.

```<code>trait A1 {
  self: B =>

  def doit {
    println(bar)
  }
}

trait A2 extends B {
  def doit {
    println(bar)
  }
}

trait B {
  def bar = "default bar"
}

trait BX extends B {
  override def bar = "bar bx"
}

trait BY extends B {
  override def bar = "bar by"
}

object Test extends App {
  // object Thing1 extends A1  // FAIL: does not conform to A1 self-type
  object Thing1 extends A1 with B
  object Thing2 extends A2

  object Thing1X extends A1 with BX
  object Thing1Y extends A1 with BY
  object Thing2X extends A2 with BX
  object Thing2Y extends A2 with BY

  Thing1.doit  // default bar
  Thing2.doit  // default bar
  Thing1X.doit // bar bx
  Thing1Y.doit // bar by
  Thing2X.doit // bar bx
  Thing2Y.doit // bar by

  // up-cast
  val a1: A1 = Thing1Y
  val a2: A2 = Thing2Y

  // println(a1.bar)    // FAIL: not visible
  println(a2.bar)       // bar bx
  // println(a2.bary)   // FAIL: not visible
  println(Thing2Y.bary) // 42
}
</code>```

One important difference IMO is that A1 does not expose that it is needs B to anything that merely sees it as A1 (like illustrated in the up-cast parts). The only code that will actually see that a particular specialisation of B is used, is code that explicitly knows about the composed type (like Think*{X,Y}).

Another point is that A2 (with extension) will actually use B if nothing else is specified while A1 (self-type) does not say that it will use B unless overridden, a concrete B must explicitly be given when objects are instantiated.

Body:
I have some code that illustrates some of the differences wrt visibility and "default" implementations when extending vs setting a self-type. It does not illustrate any of the parts discussed already about how actual name collisions are resolved, but instead focuses on what is possible and not possible to do.

trait A1 {
  self: B =>

  def doit {
    println(bar)
  }
}

trait A2 extends B {
  def doit {
    println(bar)
  }
}

trait B {
  def bar = "default bar"
}

trait BX extends B {
  override def bar = "bar bx"
}

trait BY extends B {
  override def bar = "bar by"
}

object Test extends App {
  // object Thing1 extends A1  // FAIL: does not conform to A1 self-type
  object Thing1 extends A1 with B
  object Thing2 extends A2

  object Thing1X extends A1 with BX
  object Thing1Y extends A1 with BY
  object Thing2X extends A2 with BX
  object Thing2Y extends A2 with BY

  Thing1.doit  // default bar
  Thing2.doit  // default bar
  Thing1X.doit // bar bx
  Thing1Y.doit // bar by
  Thing2X.doit // bar bx
  Thing2Y.doit // bar by

  // up-cast
  val a1: A1 = Thing1Y
  val a2: A2 = Thing2Y

  // println(a1.bar)    // FAIL: not visible
  println(a2.bar)       // bar bx
  // println(a2.bary)   // FAIL: not visible
  println(Thing2Y.bary) // 42
}

One important difference IMO is that A1 does not expose that it is needs B to anything that merely sees it as A1 (like illustrated in the up-cast parts). The only code that will actually see that a particular specialisation of B is used, is code that explicitly knows about the composed type (like Think*{X,Y}).

Another point is that A2 (with extension) will actually use B if nothing else is specified while A1 (self-type) does not say that it will use B unless overridden, a concrete B must explicitly be given when objects are instantiated.


答:
A couple of thoughts:

It's better if game components don't know how to draw themselves. A class should have only one reason to change; here your components may change if you need to change what they do in-game, and they could change if you need to change how they're drawn as well.

For this scenario the most straightforward solution is use instanceof. It's not the most general solution but it's the simplest thing that'll solve this particular problem.

```<code>for (GameComponent component : gameComponents) {
    if (component instanceof Drawable) {
        ((Drawable) component).draw();
    }
    if (component instanceof Updatable) {
        ((Updatable) component).update();
    }
}
</code>```

If you have a finite set of GameComponent types, what you want is a sum type, which mainstream OOP languages don't provide native support for but you can kind of emulate through the Visitor Pattern. (There's an alternative way of implementing them but it won't be elegant in Java; it works best with named arguments and lambda expressions.) This is a more general solution to taking decisions based on the particular kind of GameComponent because it gives you full access to the component type.

It would look something like this:

```<code>    public interface ComponentVisitor {
         void visit(Foo foo);
         void visit(Bar bar);
         void visit(Baz baz);
    }

    public abstract class GameComponent {
        // prevent subclassing outside this scope
        private GameComponent() {}

        public abstract void accept(ComponentVisitor visitor);

        public static final class Foo extends GameComponent implements Drawable, Updatable {
            // implement ...

            public void accept(Componentvisitor visitor) {
                visitor.visit(this);
            }
        }

        public static final class Bar extends GameComponent implements Updatable {
            // implement ...

            public void accept(Componentvisitor visitor) {
                visitor.visit(this);
            }
        }

        public static final class Baz extends GameComponent {
            // implement ...

            public void accept(Componentvisitor visitor) {
                visitor.visit(this);
            }
        }
    }
</code>```

Now you can take component-specific decisions like this:

```<code>    for (GameComponent component : gameComponents) {
        component.accept(new ComponentVisitor() {
            public void visit(Foo foo) {
                // do something Foo-specific here
            }

            public void visit(Bar bar) {
                // do something Bar-specific here
            }

            public void visit(Baz baz) {
                // do something Baz-specific here
            }
        });
    }
</code>```

This works because any component needs to implement accept, and for visit(this) to compile the Visitor needs to have a method that accepts that particular kind of component. It's still possible to implement a component such that accept doesn't call visit(this), so we safeguard against that by using a private constructor. That prevents outside subclassing while allowing subclassing of inner classes (because inner classes have access to private members of their enclosing class.) The end result is a finite set of components and an exhaustive way to discriminate between them (you can't forget to handle one of them because the Visitor implementation wouldn't compile.)

Title: Empty superclass for Collection of derived classes

Body:
Basically, what I would like to obtain is a way to iterate through ONE list, and call methods specific to the interface the objects in the collection implement.

In my Java project, it would result in something like this:

```<code>//GameComponent would be my empty abstract class
HashSet<GameComponent> components = new HashSet<GameComponent>();
components.add(/* instance of a class that extends GameComponent and implements Drawable || Updatable */);

for (Drawable d : components)
    d.draw();

for (Updatable u : components)
    u.update();
</code>```

My friends suggested me to just make two separate lists, but that means some objects will be in both lists.

I also think that it makes sense (abstraction-wise) to have one list of GameComponents and iterate through that one list.

But I also don't like having an empty class to inherit from, only for categorisation.

So, the question is: does my approach make sense? If so, is it elegant? If not, what pattern could I follow?

Body:
A couple of thoughts:

It's better if game components don't know how to draw themselves. A class should have only one reason to change; here your components may change if you need to change what they do in-game, and they could change if you need to change how they're drawn as well.

For this scenario the most straightforward solution is use instanceof. It's not the most general solution but it's the simplest thing that'll solve this particular problem.

for (GameComponent component : gameComponents) {
    if (component instanceof Drawable) {
        ((Drawable) component).draw();
    }
    if (component instanceof Updatable) {
        ((Updatable) component).update();
    }
}

If you have a finite set of GameComponent types, what you want is a sum type, which mainstream OOP languages don't provide native support for but you can kind of emulate through the Visitor Pattern. (There's an alternative way of implementing them but it won't be elegant in Java; it works best with named arguments and lambda expressions.) This is a more general solution to taking decisions based on the particular kind of GameComponent because it gives you full access to the component type.

It would look something like this:

    public interface ComponentVisitor {
         void visit(Foo foo);
         void visit(Bar bar);
         void visit(Baz baz);
    }

    public abstract class GameComponent {
        // prevent subclassing outside this scope
        private GameComponent() {}

        public abstract void accept(ComponentVisitor visitor);

        public static final class Foo extends GameComponent implements Drawable, Updatable {
            // implement ...

            public void accept(Componentvisitor visitor) {
                visitor.visit(this);
            }
        }

        public static final class Bar extends GameComponent implements Updatable {
            // implement ...

            public void accept(Componentvisitor visitor) {
                visitor.visit(this);
            }
        }

        public static final class Baz extends GameComponent {
            // implement ...

            public void accept(Componentvisitor visitor) {
                visitor.visit(this);
            }
        }
    }

Now you can take component-specific decisions like this:

    for (GameComponent component : gameComponents) {
        component.accept(new ComponentVisitor() {
            public void visit(Foo foo) {
                // do something Foo-specific here
            }

            public void visit(Bar bar) {
                // do something Bar-specific here
            }

            public void visit(Baz baz) {
                // do something Baz-specific here
            }
        });
    }

This works because any component needs to implement accept, and for visit(this) to compile the Visitor needs to have a method that accepts that particular kind of component. It's still possible to implement a component such that accept doesn't call visit(this), so we safeguard against that by using a private constructor. That prevents outside subclassing while allowing subclassing of inner classes (because inner classes have access to private members of their enclosing class.) The end result is a finite set of components and an exhaustive way to discriminate between them (you can't forget to handle one of them because the Visitor implementation wouldn't compile.)


问:
I want to draw class diagram, but I don't know how to put server and database inside?
I just started to draw class diagram, I think it is based on 3-tie architecture. I have mobile application, servers, database, and web interface.

But I do not know if it should put the server in? I just want to write a high-level one.

答:
A server or database doesn't go into a class diagram. A class diagram, at the highest level, shows the classes and their relationships with each other. Adding more detail would first indicate public members, and even more detail would indicate private members of the class. You may show classes that interact with the database (your data model, as an example), but you wouldn't actually show a database.

A deployment diagram would show which pieces of your system reside on what physical nodes. For example, you could have a "mobile application" node (which may be further detailed by other diagrams) that would reside on types of mobile devices, a web application that resides on web servers, and linkages between web servers and database servers.

A component diagram could be used to indicate pieces that communicate with a database, as well.


答:
But when the other columns are same in value, it doesn't matter which is returned.

I'd agree with that.

Some DBMSs implement "aggregate" functions like FIRST and LAST to keep the "purity" of the select statement but, if the values really are the same, then it should make no difference at all and MIN or MAX will do just as well.

Of course, you can never guarantee that they're going to stay the same ...

Title: Return multiple columns with SQL where GroupBy is on one column

Body:
I have noticed that all the columns in a SQL Select Query should be in a aggregate function, because otherwise the output value for group would be arbitrary.

This makes sense. But when the other columns are same in value, it doesn't matter which is returned. Is there a way to specify this or just use MAX() or MIN() on varchar columns?


问:
Branch per feature: What are the actual benefits (and risks)?
I've read quite a lot of posts lately about different branching strategies (e.g a lot of links from To branch or not to branch?), and while almost every article explains on how to do this or that strategy they rarely explain the why.

Currently our team is investigating whether or not to switch to "feature branches". We're currently using a "everyone commits to trunk" model and we have release branches, which we use to do hotfixes to previous releases. All in all, this model has worked very well in the past. So actually I'd say - if it ain't broken, don't fix it.

However, there might be a point that I'm missing, so I'd like to ask: What are actual tangible benefits of using a feature branch strategy over "everyone commits to trunk"? What are the drawbacks of feature branches in your experience?

答:
Assume that you're working on a feature in a seperate branch. Then for some reason, you need to make a completely unrelated change somewhere else; say you're fixing the build.

With feature branches, you can just commit your current work in your branch, switch to default, make your fix and switch back.

Without feature branches, you either have to very selectively choose which files you want to commit (which can go wrong very easily), or you have to stash your current work (but stashes can be finicky), or you have to just push unfinished stuff (you can imagine potential consequences).

Another useful scenario is where you have to do some work that would touch a lot of the code, something you'd be working on for some time. Usually these are big refactorings.

If you do this sort of stuff in a branch, you can work in isolation, not disturbing others with your changes, but still frequently commit and sync with the default branch.

Branches provide a very good safety net and I can tell that we've had a lot less merge conflicts and general friction since we started using them. But your mileage may vary.


答:
The advantages are obvious - you work on features independently, and so they never affect anyone else's work until it comes time to merge. You can do code reviews and targeted testing on the feature branch without holding anyone else up if there's a problem.

The disadvantages: firstly, you do have to merge and while that's not a problem with tools like Subversion, git or similar, it can be a right pain with some tools. You also have to consider that even with tools that support merging well, its not necessarily a pain-free process. If you have to merge binary files (eg images, icons etc) or you're merging files that have also been changed, then you will have to spend a little extra time managing the merge.

The other disadvantage is that you might add something to a feature branch that you'd like to use, you either have to merge that feature branch to your current one, or wait for it to get merged to trunk (and then merge it), so there is scope to get a little out of date with regard to other work.

Both disadvantages aren't particularly onerous as long as you don't expect feature branches to be worked on and then left for a long time before merging back to trunk. I think they're probably a better way of working compared to the develop/main/release model, and especially to the 'work on trunk' model typified by tools like Sourcesafe.

That said, there's no reason not to fix something that isn't broken. If your team is suited to your current process and you have no issues with it, then continue to use it.

Title: Branch per feature: What are the actual benefits (and risks)?

Body:
I've read quite a lot of posts lately about different branching strategies (e.g a lot of links from To branch or not to branch?), and while almost every article explains on how to do this or that strategy they rarely explain the why.

Currently our team is investigating whether or not to switch to "feature branches". We're currently using a "everyone commits to trunk" model and we have release branches, which we use to do hotfixes to previous releases. All in all, this model has worked very well in the past. So actually I'd say - if it ain't broken, don't fix it.

However, there might be a point that I'm missing, so I'd like to ask: What are actual tangible benefits of using a feature branch strategy over "everyone commits to trunk"? What are the drawbacks of feature branches in your experience?


答:
It depends what source control system you are using.
In some distributed source control systems like Git and Mercurial branches are very lightweight and I usually create branch per feature while using one of these systems. It is very convenient and relatively easy to maintain. You can easily make different experiments with your source code and share these results to others.

Also branching is useful when you are working on large feature and need to perform some support tasks with existing code. You can easily switch from your feature branch to default branch, make fix in default branch, switch back and continue working on your feature. Of course you should take changes from default branch periodically.

However, some source control systems do not support lightweight branches and copy entire directory with source code. In this case branching per feature is really pain when your codebase has large size.


问:
When to use a Singleton and when to use a static class
I've searched about this here and on StackOverflow and found some differences between the two.

But I'm still not sure in what cases one would prefer a Singleton, and in what cases one would choose to use a static class.

(In languages which don't support 'static classes', like Java, I'm obviously referring to classes containing only static methods and fields).

Please give me concrete examples of cases where you would pick each one, and explain why.

答:
A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object. An example could be the Math class in Java. It contains a whole bunch of related functions that are accessed outside the context of any specific object instance. I've done similar things where a set of common utility functions that are used in multiple places in an application are grouped together into a single utility class.

A singleton is used when you do want an actual object (with its own internal state and everything), and you want to limit your system to exactly one instance of that object. This might be useful if you have some kind of shared resource, such as a database, an in-memory cache, or maybe some specialized piece of hardware like a robotic arm. Many parts of your program might want to use this resource and you might want to have all access to the resource go through a single point. A singleton isn't always the only way to handle these situations, but it's one of the few places I think a singleton might be a good choice.


答:
Singletons objects made so there can only be 1 instance at any given time and can be used application wide.

Objects that handle stuff like connection pools are a good candidate to be Singletons;

You only want 1 instance in the entire application

you must be able to access it from different parts of the application

the data it holds has to be persisted even when no other objects are currently pointing to it (handy when you want to reuse objects that are expensive to initialize).

A class filled with only static methods is not something that's usually meant to be initialized like an object. It's more like a wrapper for the static methods in it.

An example of this that I use frequently is a utility class with methods that do repetitive tasks that take parameters, does a calculation with them/formats them/etc. and then returns the result, without using any external (or at least no non-static) fields or methods.
I never initialize a utility class, I just use the static methods in it for all repetitive methods.

This is just how I tend to use Singletons and static (method filled) classes, not sure if it confirms to any "official" standards...

Title: When to use a Singleton and when to use a static class

Body:
I've searched about this here and on StackOverflow and found some differences between the two.

But I'm still not sure in what cases one would prefer a Singleton, and in what cases one would choose to use a static class.

(In languages which don't support 'static classes', like Java, I'm obviously referring to classes containing only static methods and fields).

Please give me concrete examples of cases where you would pick each one, and explain why.


答:
Avoid the Gang of Four Singleton pattern, for reasons cited in the other answers. Mainly it is an anti-pattern based on difficulties it creates for testing.

Factory and Dependency Injection made Singleton obsolete. The best answer is to use a Factory that decides whether to instantiate one instance, or many, of a given class. That way, the class and its clients aren't responsible for its singleton status -- that becomes a transparent concern managed by the Factory.

Dependency injection frameworks like Spring do that for you out of the box (e.g. Spring beans are singletons unless you specify otherwise).

Purely static classes are problematic for both testing and using OO concepts. I've seen teams with an irresistible urge to make everything static and final, and the question becomes, why aren't they just writing C code?

If your static class has side effects, then it should not be static. That means, if it's managing shared state, or if it's changing the state of parameters, then it should be a regular class where the Factory hands out a single shared instance. A purely static class that manages shared state becomes a really hard problem for testing.

A purely static class also creates hard, compile-time dependencies on that particular class, which really compromises the extend-ability and test-ability of your code. Seems like you'd want to reserve that for something eternal and unchanging, with no side effects, like math formulas.

So the answer is, don't write classes as singletons, but rather move that decision into your Factory. And in an OO language, static classes miss some of the most important design aspects of the language and complicate testing. Again, you can use worker classes with specific semantics to bundle those up and have them generated by your Factory.


问:
Export to Excel - threading
I am working on an ASP.NET application. One requirement by the users is they are capable of exporting to Excel of some UIs. I have worked on them using the Infragistics library, and I have supplied them with the exports they want.

However, some of the UIs they see are so complex that it takes a great amount of time to be accomplished (for a web application experience). For instance, an export may take a few minutes, like 4-5 minutes.

I was wondering, if there would be a way, in which I could make this task to be done asynchronously, using threads and make it to last shorter.

答:
I suspect that if you introduce threading to the export-to-Excel process that you'll now have two problems on your hands instead of just one.

You need to take a deep look into the export code, and preferably run it through a profiler so you can see where time is being spent.  Once you know where the bottlenecks are, you can apply the right technology to resolve the issue.

Throwing threads at an unknown problem has a greater probability of making things (much) worse.

While you are investigating what the root of the issue is, you can consider moving the export-to-Excel process into a background process that can run independently of the user's session.  Moving to a background process won't fix the wait time or the user's perceptions of things, but it will at least allow the user to go work on something else while they wait for the export to complete.

As Doc Brown pointed out, using background threads is a fairly common technique to free up the main thread.  Using a background thread in this way generally doesn't introduce the potential pitfalls associated with threading an export process.  And you can move the process to the background without introducing much if any at all of the mental overhead that comes from using asynchronous threads.

Title: Export to Excel - threading


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
I always browse with JavaScript enabled and have since the dawn of the web browser. </p>

<p>Never once have I had a single issue that was worth degrading my browser experience over. Perhaps a few pop-ups or other annoyances, but the benefits far outweigh the risks in my opinion. </p>

Body:
I always browse with JavaScript enabled and have since the dawn of the web browser.

Never once have I had a single issue that was worth degrading my browser experience over. Perhaps a few pop-ups or other annoyances, but the benefits far outweigh the risks in my opinion.


答:
I see no problems with this.

For example, when I login I'll end up with a login result:

```<code>public abstract class LoginResult { ... }
</code>```

When I login, I might have three scenarios:

Login failed as password doesn't match

Login succeeded

Login succeeded, but account is banned

To accomplish this, I would then introduce three classes that inherit from the base:

```<code>public class SuccessfulLoginResult : LoginResult
{
   // May contain a string with a welcome message
}
</code>```

One for when login fails:

```<code>public class FailedLoginResult : LoginResult
{
    // String containing information as to why the login has failed and integer property indicating how many login attempts are left
}
</code>```

One for when account is banned:

```<code>public class AccountSuspendedLoginResult : LoginResult
{
   // String containing information as to why account is suspended and potentially a date time field indicating when account will be activated again
}
</code>```

I would then use it in the following way (C#):

var loginResult = _accounts.Login("Username", "Password");

```<code>if (loginResult is SuccessfuLoginResult)
{
   // Do something
}
else if (loginResult is FailedLoginResult)
{
   // Do something else
}
</code>```

Base class can stay empty and I see no problems with that.

Body:
I see no problems with this.

For example, when I login I'll end up with a login result:

public abstract class LoginResult { ... }

When I login, I might have three scenarios:

Login failed as password doesn't match

Login succeeded

Login succeeded, but account is banned

To accomplish this, I would then introduce three classes that inherit from the base:

public class SuccessfulLoginResult : LoginResult
{
   // May contain a string with a welcome message
}

One for when login fails:

public class FailedLoginResult : LoginResult
{
    // String containing information as to why the login has failed and integer property indicating how many login attempts are left
}

One for when account is banned:

public class AccountSuspendedLoginResult : LoginResult
{
   // String containing information as to why account is suspended and potentially a date time field indicating when account will be activated again
}

I would then use it in the following way (C#):

var loginResult = _accounts.Login("Username", "Password");

if (loginResult is SuccessfuLoginResult)
{
   // Do something
}
else if (loginResult is FailedLoginResult)
{
   // Do something else
}

Base class can stay empty and I see no problems with that.


问:
Pooling (Singleton) Objects Against Connection Pools
Given the following scenario

A canned enterprise application that maintains its own connection pool

A homegrown client application to the enterprise app. This app is built using Spring framework, with the DAO pattern

While I may have a simplistic view of this, I think the following line of thinking is sound:

Having a fixed pool of DAO objects, holding on to connection objects from the pool. Clearly, the pool should be capable of scaling up (or down depending on need) and the connection objects must outnumber the DAOs by a healthy margin. Good

Instantiating brand new DAOs for every request to access the enterprise app; each DAO will attempt to grab a connection from the pool and release it when it's done. Bad

Since these are service objects, there will be no (mutable) state held by the objects (reduced risk of concurrency issues)

I also think that with #1, there should be little to no resource contention, while in #2, there'll almost always be a DAO waiting to be serviced. Is my thinking correct and what could go wrong?

答:
Entity Framework and Linq to SQL both instantiate DAO's as needed.

DAO's in Entity Framework (they're called Data Contexts) are deliberately designed to be lightweight to instantiate, so you create a new one each time a data access is required. Sometimes folks try to cache these Data Contexts, but that is a design error, and it can cause concurrency problems (DataContext is not thread-safe).  In general, you create one DataContext object for each Unit of Work.

Entity Framework is most commonly used with SQL Server; SQL Server maintains a pool of "recently-used connections" that can be reused, so that the process of opening a new connection is also as fast as possible.

Further Reading

Linq to SQL DataContext Lifetime Management

Building N-Tier Applications with Entity Framework ... for various approaches.


问:
Gathering IP address and workstation information; does it belong in a state class?
I'm writing an enterprisey utility that collects exception information and writes to the Windows Event Log, sends an email, etc. This utility class will be used by all applications in the corporation: web, BizTalk, Windows Services, etc.

Currently this class:

holds state given to it via public properties

calls out to .NET Framework methods to gather information about runtime details. Included are call to various properties and methods from System.Environment, Reflection details, etc.

This implementation has the benefit of allowing all those callers not to have to make these same calls themselves. This means less code for the caller to forget, screw up, etc.

Should this state class (please what's the phrase I'm looking for [like DTO]?) know how to resolve/determine runtime details (like the IP address and machine name that it's running on)?

It seems to me on second thought that it's meant to be a class that should hold state, and not know how to call out to the .NET Framework to find information.

```<code>var myEx = new AppProblem{MachineName="Riker"};

//Will get "Riker 10.0.0.1" from property MachineLongDesc
Console.WriteLine("full machine details: " + myEx.MachineLongDesc);

public class AppProblem
{
    public string MachineName{get;set;}
    public string MachineLongDesc{
        get{
            if(string.IsNullOrEmpty(this.MachineName)
            {
                this.MachineName = Environment.MachineName;
            }
            return this.MachineName + " " + GetCurrentIP();
        }
    }

    private string GetCurrentIP()
    {
        return System.Net.Dns.GetHostEntry(this.MachineName)
                     .AddressList.First().ToString();
    }
}
</code>```

This code was written by hand from memory, and presented for simplicity, trying to illustrate the concept.

答:
You're creating a level of abstraction between code that generates exceptions, and code that reports exceptions. It seems to me that the interface to the lower level abstraction - that of reporting - should just include accepting objects that represent exceptions with defined methods of getting a human-readable representation.

In general, exceptions should include any context for the problem that isn't available to whatever is handling it, nothing more. If the handler has more context, it may wrap the exception with the additional info and pass it on, or just log it.

In your situation then, the error reporting utility can retrieve the additional context that it's aware of - the runtime details of the code that generated the exception - and include that in its output.

If you're concerned about putting logic in what you think should be kept to a simple DTO, add the logic as an intermediate step between accepting the exception object - maybe this is the DTO - and reporting.