问:
Not copyrighting code and then reusing functions later
I'm coding something for my job to copy directories and then use regex to make all the filenames uniform.  I'm an undergrad student programmer for my university and I'm not sure what a professional coder would consider reasonable in this case. My job is mostly to implement mathematical research.  The current assignment is outside what I've been doing and seems like it would be really useful to have some of the functions available in case I (most likely) encounter a similar assignment at some point in my career in the future.  It's going to be really useful because the current filenames are so screwed right now that the admin assistants can't really keep up (and even trying to do so might just cause more human error).  I'm thinking that it may not overall be useful outside the current assignment because the regex will be so customised to the way the file are incorrectly named.

I'm wondering if this is simple work for a pro coder, and therefore I'm making this program to be much more important in my head than it actually is, or if this is something that a coder would really want to copyright or otherwise retain the ability to use this whenever and wherever else they feel like.  They've already told me that there is no question that I'll be given credit for the work, which I'm excited about.  My only concern was whether I should be thinking about reusing this code later or if this task is so generic that a pro coder would laugh about keeping the rights to such code.

This thread was interesting but seems different from my situation:

How can I reuse generic code for consulting between companies?

EDIT:

Florida, USA

答:
You can never not copyright code.  Code is copyrighted as soon as it is written.  The real question is who owns the copyright.  The applicable area of law is known as work for hire and this is very subject to national variations.

Typically, when you work for some employer, all materials that you produce during the period of employment that is for the employer is owned by the employer (thats what you get paid to do).

If your employer licenses the code in such a way that you can use it elsewhere, then go for it.  If your employer says "no, you can't use this code", then that is the answer.

Read your contract, talk to your employer and maybe talk to a lawyer.  Don't reuse the code until you have done at least two of these things.


问:
What is a reasonable way to structure relationships in MongoDB
I am also using Node - which I am not the most familiar with - if the articles/books/tutorials pertained to this also - that would help even more.

I come from a mostly MySQL background - but in this api, all data is going to be served as JSON - so at first glance, using Mongo made a lot of sense (I could be wrong). One thign I have been unable to wrap my head around though, is relational models. e.b. Object has many Assets.

To use some examples most people would be familiar with, let's assume I am trying to do something like:

Select a blog post and all of its comments. or

Select a photo gallery and all of its photos

Is it as simple as storing a call back inside of my assets like this?:

```<code>Photo {
    __id: 5,
    content: '...',
    gallery_id: 9
}
</code>```

And performing a .find({ gallery_id: 9 })?

I know this would work, but is that best practice? I am very new to Document Databases, and have not seen much on this particular topic.

答:
Coincidentally, I am in the process of thinking through a new application using Node and MongoDB.

I have lightly used MongoDB in the past and found the MongoDB documentation data modeling to be a great starting point.  The approach that you describe, storing a reference in the parent and using a second find to get the referenced items, is a perfectly good way to go about it, if you choose to make use of references rather than directly embedding the children in the parent object.

However, there might be some better ways to go at this.  I have been looking into using Mongoose as an Object Document Mapper (ODM).  It is the officially supported ODM for Node per the MongoDB documentation.

It provides a number of useful features, particularly if you are building a fairly complex model within the application, including pseudo-joins using the populate function. The population capability provides a more structured approach to managing references allowing for retrieval of parent and children in one step.

ContentLicense: CC BY-SA 3.0


问:
Confusion with Factory pattern regarding Liskov's Substitution Principle, code maintainability and Unit Testing?
I have a confusion regarding Factory Pattern there are basically two ways You can implement that.

Approach 1:

```<code>public interface IProductFactory
{
    IProduct GetProductA();
    IProduct GetProductB();
    IProduct GetProductC();
}

public class ProductFactory : IProductFactory
{
    public IProduct GetProductA()
    {
        //some implementation goes here
    }
    public IProduct GetProductB()
    {
        //some implementation goes here
    }
    public IProduct GetProductC()
    {
        //some implementation goes here
    }
}
</code>```

Approach 2:

```<code>public enum ProductType
{
    ProductA = 1,
    ProductB = 2,
    ProductC = 3
}

public interface IProductFactory
{
    IProduct GetProduct(ProductType productType);
}

public class ProductFactory : IProductFactory
{
    public IProduct GetProduct(ProductType productType)
    {
        switch (productType)
        {
            case ProductType.ProductA:
                //return IProduct with specific implementation
                break;
            case ProductType.ProductB:
                //return IProduct with specific implementation
                break;
            case ProductType.ProductC:
                //return IProduct with specific implementation
                break;
            default:
            //return null
        }
    }
}
</code>```

Pros of both approaches

Approach 1:

benefit of compile time checks that the implementation class will be
forced to provide the corresponding methods.

Approach 2:

Implementation will have a benefit of shorter no. of lines of code.

Interface does not become fragile, it won't change as the new
products keep on adding.

Cons of both approaches

Approach 1:

Lines of code becomes large.

As more number of Products are implemented, the interface changes
and hence it is hard to follow Liskov's Substitution Principle.

Approach 2:

Since it is hiding internal details of GetProduct, it is hard to
tell what the Factory will return when a specific type of enum is
passed.

You might get into run time exceptions

I am still struggling to decide on which approach to use?

Note: I am only aware of these two approaches, there might be different approaches also.

答:
Both approaches break Liskov Substitution Principle. Correct implementation will look smth. like:</p>

```<code>public interface IProductFactory
{
    IProduct GetProduct();
}

public class Product1Factory : IProductFactory
{
    public IProduct GetProduct()
    {
        return new Product1(); //configure instance here
    }
}

public class Product2Factory : IProductFactory
{
    public IProduct GetProduct()
    {
        return new Product2(); //configure instance here
    }
}

public class Product3Factory : IProductFactory
{
    public IProduct GetProduct() //configure instance here
    {
        return new Product3();
    }
}
</code>```

OwnerDisplayName: shankbond

Body:
Both approaches break Liskov Substitution Principle. Correct implementation will look smth. like:

public interface IProductFactory
{
    IProduct GetProduct();
}

public class Product1Factory : IProductFactory
{
    public IProduct GetProduct()
    {
        return new Product1(); //configure instance here
    }
}

public class Product2Factory : IProductFactory
{
    public IProduct GetProduct()
    {
        return new Product2(); //configure instance here
    }
}

public class Product3Factory : IProductFactory
{
    public IProduct GetProduct() //configure instance here
    {
        return new Product3();
    }
}

OwnerDisplayName: almaz


问:
Importance of diffing and merging for design specifications documentation
The context of this question is choosing tools for writing design specifications for software projects.

These documents will be written and maintained by architects and developers, I'm not talking about marketing requirements. Some of them may be shared outside the team, but only in a processed, non-editable form (PDF, all the docs are assumed being able to be exported to this format).

These are architecture documents, describing the structure of code components, implementation methods, protocols, data formats, etc. They take the form of text with diagrams and identifier names and the occasional code snippets, this isn't about API documentation that might be generated from source files.

The docs will be under source control, fortunately nobody here needs to be educated about that. It's inevitable that versioning will arise over time: we do maintain old versions of the software. Issue tracking might not be adhered to as strictly for documentation as for code.

How important is it to be able to easily compare and merge such documents? We have diverging opinions in the team, ranging from “nobody ever merges documentation and if needed Word has a merge tool” to “merging is crucial and git merge must work”. Note “Word has a merge tool” is something that I quote but don't agree with, having had the painful experience of merging two bugfixes that I had made to two copies of the same document

I have a vague memory of a rule in some company (Google, perhaps, since it's so often cited) that “if you can't merge it, it doesn't exist”, but I'm unable to find it now.

I'm looking for either well-reasoned arguments, or authoritative-looking (and preferably motivated) citations.

答:
To answer you question properly, we first have to assess whether easily could ever be used to describe the process of comparing and merging of documents.

Documents are not code. There are many obvious differences between merging code and merging documents, but some subtle ones also: if a mistake is made when merging code there are many automated ways of detecting this, ranging from compiler errors to formal unit-testing. Conversely, with documents, a visual inspection will almost always be required; just because document parts don’t appear to conflict, (and still conform to DITA rules in this scenario) there is no guarantee that a change in a title (or even the way it is rendered) in one part of the document can leave another part redundant or invalid.

The above is an excerpt from a recent blog post by myself:

Reviewing XML Documents for an N-Way Merge

N-Way merging was considered because documents have narrative content. As such, they are often edited and reviewed in a more ad-hoc way to code that has a very strict structure (so far as a compiler or interpreter is concerned).

My view after working on a solution for this problem is that this kind of merge is unlikely ever to be 'easy' but it is certainly possible to make it manageable.

To help illustrate some of the challenges, here is one view of a prototype web app (the one used for the blog) for exploring review methods for an N-Way document merge:


问:
In a declarative language, specifically in the context of modelling, can we make a clear distinction between code and data?
For declarative languages, specifically (but not limited to) in the field of modelling, it's not obvious to me whether code can be considered to be separate from data. This line of reasoning may only apply to non-turing complete languages such as NeuroML.

Say for instance I had a very domain specific declarative language which I used to described the positions of planets and their velocities, and I described a system of three orbiting bodies:

```<code>satellite planet_earth,moon,sun {

planet_earth.position = [6,0,0]

planet_earth.velocity = [0,23,-32]

planet_earth.mass = 1e3

moon.position = [6,0,0.0001]

moon.velocity = [0,0,3]

moon.mass = 1e2

sun.position = [0,0,0]

sun.velocity = [0,0,0]

sun.mass = 1e12 }
</code>```

This language could be passed to a simulator which then simulated the motion of the planets.

From one perspective this is code - It is describing initial conditions and consequently within the constraints of the language a sequence of steps for a computer to run. From another perspective it is 'data' - it is a description of a physical system.

Is this concept (is something code or data) something which has been studied much? I've looked into it

答:
I don't see a difference between declarative and imperative languages within the context of your question, so I'll try answering your question in a more general way.

The distinction between code and data is a conceptual one, there is no clear, objective, definition which is applicable to every situation; there will always be cases where different individuals will come to different conclusions.

Consider the the following C++ code:

```<code>std::vector<std::string> names = { "Smith", "Miller", "Watson" };
</code>```

Are the strings data (because they're just embedded strings) or code (because they're part of the source code)?

There are languages in which the code representation is a first-class type of the programming language. These languages are typically homoiconic (i.e., their syntax is very similar to the abstract syntax tree); the archetypal example is Lisp. In these languages, the distinction between code and data is even more blurred.

Body:
I don't see a difference between declarative and imperative languages within the context of your question, so I'll try answering your question in a more general way.

The distinction between code and data is a conceptual one, there is no clear, objective, definition which is applicable to every situation; there will always be cases where different individuals will come to different conclusions.

Consider the the following C++ code:

std::vector<std::string> names = { "Smith", "Miller", "Watson" };

Are the strings data (because they're just embedded strings) or code (because they're part of the source code)?

There are languages in which the code representation is a first-class type of the programming language. These languages are typically homoiconic (i.e., their syntax is very similar to the abstract syntax tree); the archetypal example is Lisp. In these languages, the distinction between code and data is even more blurred.


问:
Whats the real overhead of TDD once the entire team is used to it?
What percentage of time is saved and costed doing TDD.

I assume this percentage of cost and reward changes during a projects life-cycle.

I'd imagine the initial phase has a lot more cost but little rewards attached. Further on (during re-factoring) you get the benefit of your tests.

I've heard anywhere from 30-50% of your time is writing unit tests. However that doesn't take into account the time saved from writing those tests. Whats the time saved as well as the time cost? In bug fixing and refactorablity?

答: In our case, I'd estimate it's close to 40%.  However, I don't think we went through a phase where it was any more than this.  We have a code generator that spits out both a code skeleton that gets fleshed out by the developers and a test suite that likewise gets fleshed out.  Most of our testing effort actually goes into tracking down (or creating) appropriate test data to ensure that we get complete coverage.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


答:
Approach 2 is the classical Factory Pattern. This pattern is nothing to do with LSP. To ensure LSP is not violated in the client programs, you need to carefully design IProduct interface in such a way that the client program that is operating on IProduct would continue to operate without any modification irrespective of the concrete product that actually implements IProduct. If, you observe you are violating LSP redesign the interfaces.

For example it may be better to create one interface for a category of products if these categories differ in the way client communicates with them.

```<code>public interface IPerfume
{
    //Methods specific perfume products
}

public interface IAutomobile
{
    //Methods specific to automobiles
}
</code>```

Then, you define one factory for each category of products. PerfumeFactory to create perfume products and AutomobileFactory to create automobiles.

The example may not sound fancy but that is all I can think of now.

Title: Confusion with Factory pattern regarding Liskov's Substitution Principle, code maintainability and Unit Testing?

Body:
I have a confusion regarding Factory Pattern there are basically two ways You can implement that.

Approach 1:

```<code>public interface IProductFactory
{
    IProduct GetProductA();
    IProduct GetProductB();
    IProduct GetProductC();
}

public class ProductFactory : IProductFactory
{
    public IProduct GetProductA()
    {
        //some implementation goes here
    }
    public IProduct GetProductB()
    {
        //some implementation goes here
    }
    public IProduct GetProductC()
    {
        //some implementation goes here
    }
}
</code>```

Approach 2:

```<code>public enum ProductType
{
    ProductA = 1,
    ProductB = 2,
    ProductC = 3
}

public interface IProductFactory
{
    IProduct GetProduct(ProductType productType);
}

public class ProductFactory : IProductFactory
{
    public IProduct GetProduct(ProductType productType)
    {
        switch (productType)
        {
            case ProductType.ProductA:
                //return IProduct with specific implementation
                break;
            case ProductType.ProductB:
                //return IProduct with specific implementation
                break;
            case ProductType.ProductC:
                //return IProduct with specific implementation
                break;
            default:
            //return null
        }
    }
}
</code>```

Pros of both approaches

Approach 1:

benefit of compile time checks that the implementation class will be
forced to provide the corresponding methods.

Approach 2:

Implementation will have a benefit of shorter no. of lines of code.

Interface does not become fragile, it won't change as the new
products keep on adding.

Cons of both approaches

Approach 1:

Lines of code becomes large.

As more number of Products are implemented, the interface changes
and hence it is hard to follow Liskov's Substitution Principle.

Approach 2:

Since it is hiding internal details of GetProduct, it is hard to
tell what the Factory will return when a specific type of enum is
passed.

You might get into run time exceptions

I am still struggling to decide on which approach to use?

Note: I am only aware of these two approaches, there might be different approaches also.

Body:
Approach 2 is the classical Factory Pattern. This pattern is nothing to do with LSP. To ensure LSP is not violated in the client programs, you need to carefully design IProduct interface in such a way that the client program that is operating on IProduct would continue to operate without any modification irrespective of the concrete product that actually implements IProduct. If, you observe you are violating LSP redesign the interfaces.

For example it may be better to create one interface for a category of products if these categories differ in the way client communicates with them.

public interface IPerfume
{
    //Methods specific perfume products
}

public interface IAutomobile
{
    //Methods specific to automobiles
}

Then, you define one factory for each category of products. PerfumeFactory to create perfume products and AutomobileFactory to create automobiles.

The example may not sound fancy but that is all I can think of now.


问:
C# Logic - gaps & Islands
I am looking for help designing the display of available times for appointments (for example a hairdresser's appointment book).

Currently I have a query that returns a collection of periods that are unavailable for appointments (whether there is an existing appointment or if the service provider is closed).

So lets say Feb 3rd, from 12 to 5 is unavailable, i want to output the following string:
Jan 1st 12 am - Feb 3rd 12pm
Feb 3rd, 5pm - Dec 31 12 am.

My entire range is 1 year from Jan 1st to December 31st and there can be as many unavailable dates.

答:
If overlap is not allowed, a rather simple process can be followed:

Add an appointment starting at 31 Dec 12 AM (ending any time).

Sort the appointments.

Initialize lastTime to 1 Jan 12 AM.

For each appointment:

Output lastTime to the start of this appointment.

Set lastTime = the end of this appointment.

If overlap is allowed, this requires a sweep-line algorithm:

Split the appointments into start and end times and sort them.

If a start time and an end time are equal, put the start time first (otherwise you may get 0 duration outputs).

Add 31 Dec 12 AM as a start time.

Initialize lastTime to 1 Jan 12 AM.

Initialize a count variable to 0. This variable will, at any time, indicate how many appointments are busy at the current point in time.

Iterate through the times.

If we encounter a start time:

If count = 0, output lastTime to this time.

Increment count.

If we encounter an end time:

Decrement count.

Set lastTime to this time.

If the appointments can go beyond the given range, that should be simple enough to deal with:

For the first algorithm, start at the first appointment that ends after 1 Jan 12 AM and end before any appointment after 31 Dec 12 AM.

For the second, just initialize count to the number of appointments that runs through 1 Jan 12 AM and ignore points outside the given range.

Title: C# Logic - gaps & Islands


问:
What is a battery backup up cache?
I've read an article about Innodb performance optimization an in that post the author was repeatedly mentioning someting named a "battery back up cache". It is not clear for me what he was talking about and google did not help either. My guess is that this is some kind of backup storage in case there is a power outage. Am I right?</p>

答:
RAID arrays use a battery backed cache, so they can process data faster than they can write it. Without the battery, they couldn't do caching without risk of data loss during a power failure.

That's the only instance I can think of where you'd need a cache that is specifically battery backed. If it was backing volatile memory, it wouldn't matter.

I suppose I should note that this is a feature of a professional-grade hardware RAID setup, and not a software or consumer-grade "on board" RAID. The batteries are substantial, around the size of an altoids tin. They tend to go bad every 4-5 years, which kills your caching, and deals a performance hit to your backing store.

Title: What is a battery backup up cache?


问:
How to promote Scala to the management?
As a developer I like Scala and could tell the management about technical benefits of the language. But even if management understands that a superior technology has business impact, I fear that they don't understand what I'd be talking about.

What arguments would you present to managers with technical backgrounds (computer scientists not programming for many years)?

答:
The management understands also that new technologies bring new costs, extra training or finding other developers that know these technologies to help you in the project or to support it when you are not longer working on it.

The best way is to work on a convincing prototype during those quiet moments and/or in your free time to showcase the advantages of this new technology.
Or use it in one of the smaller projects without telling :p (depending all on company-culture)

Anyways you should have been doing this already because how could you otherwise be convinced that this new technology will provide benefits.

Title: How to promote Scala to the management?


答:
Caching is used to speed up operations.  A typical usage pattern for a user is to access the same record a couple of times.  Read it, review it, get some details on it, etc.  If the underlying system keeps whatever record in memory, even briefly, the next time the user tries to interact with the record, the access is thousands of times faster than loading it from disk again.

the problem comes when engineers get the bright idea that, to improve system performance, they will put things the user has added to the record in memory for a while.  The data is not written to disk until he cache is flushed, which could be a few seconds or maybe ten seconds, but because the cache is small and lots of changes won't fit, the possibility remains that some changes will be written to disk, while others will remain in write cache briefly.  If the power goes out while this is in limbo, the results can be devastating to the integrity of a file or database system.

So some systems implement a logical protection scheme in software, by dating changes or logging cached changes or all kind of slightly whacky things.  But if you have a battery backed write cache, well you can dispense with those things and safely know, that the write cache will always be written through.

Title: What is a battery backup up cache?

Body: I've read an article about Innodb performance optimization an in that post the author was repeatedly mentioning someting named a "battery back up cache". It is not clear for me what he was talking about and google did not help either. My guess is that this is some kind of backup storage in case there is a power outage. Am I right?</p>


问:
What to do when you're faced with a problem that you can't solve quickly?
I'm a beginner learning Java and after reading the docs I'm trying to solve some of the problems at codingbat.com. Some I managed to solve pretty quickly in a matter of seconds but some not quite. The problems themselves are easy (example http://codingbat.com/prob/p126212) but I sometimes have a hard time finding the solutions. In part because I think of the best possible solution and automatically discard the ones that might work but aren't so elegant and in part because I can't find the right algorithm. This is either due to my inexperience (I have used PHP for web development for about 2 months so I'm not a total beginner - even worked with one framework to build a website) or due to my inability to think of a good algorithm.

I normally don't look at the solutions. I sometimes get stuck even for 1 1/5 hours at simple problems and some of them I eventually solve but some I can't so I eventually look at the solution.

Is it normal/good/bad to concentrate this long if I find a problem I can't solve? I might overreact but should this be so hard for me? Is there such thing as not being able to think of algorithms even with much learning and reading?

Thank you all in advance.

答: I don't really like solving hard problems. They are complicated and confusing and easy to screw things up. So I break them up into small problems then solve those smaller problems. It works pretty well.</p>

OwnerDisplayName: Mash


答:
I think there are a couple of key things to keep in mind with respect to making the case:

Don't start by suggesting a wholesale transition to a new development language.  Figure out a way to start small and demonstrate success before suggesting a broader change.  Pick a project that you know that you can knock out of the park using Scala and can act to highlight Scala's strengths. Management is more likely to agree to an initial pilot than a full transition.

Make sure that you have clear arguments around some of the objections that are likely to come up.

With respect to Scala, you should expect push back related to finding skilled developers.  While Scala continues to gain momentum, it is a challenging language for those unfamiliar with functional programming to get their head around.  There isn't a lot of strong talent out there and not all developers can successfully transition from other languages.

You should also expect to hear about the investment in the existing code base.  If you have a large code base in another language, interoperability and leveraging that previous work will be important.  If that code base happens to be in Java, your job is a bit easier.  If not, you will need to be able to explain how Scala and your existing infrastructure can coexist. Some organizations are open to having a polyglot environment, but others can be dogmatic about having one standard which will make it more difficult to introduce something new.

Finally, you need to be able to make the case that there is a clear benefit in terms of the team's ability to deliver, at least for the subset of projects where Scala is applicable.  If you can't clearly articulate that benefit beyond your preference for it, you will have a hard time succeeding.

Title: How to promote Scala to the management?

Body:
As a developer I like Scala and could tell the management about technical benefits of the language. But even if management understands that a superior technology has business impact, I fear that they don't understand what I'd be talking about.

What arguments would you present to managers with technical backgrounds (computer scientists not programming for many years)?


问:
Changing a variable through a series of statements ... What is this technique called?
I'm looking at a function that that has several statements like this:

```<code>n = returnDifferentVersionOf(n);
</code>```

I.e., the value of the same variable n changes progressively several times during the course of a subroutine -- rather than a newly named variable being assigned at each change.

What is the generic name of this technique (if there is one)?

A more full example might be (in Ruby):

```<code># reuse same var
def cromulentize(str="")
   str = "wowza" if str.empty?
   str += " adios!"
   str = str * 3
   str.gsub!('a', 'X')
   str = str[0..-3]
   str.upcase
end
</code>```

What is that technique called, as opposed to this one:

```<code># uses diff vars
def cromulentize(str="")
   non_empty_str = str.empty? ? "wowza" : str
   adios_str = non_empty_str += " adios!"
   multiplied_str = adios_str * 3
   gsubbed_str = multiplied_str.gsub!('a', 'X')
   spliced_str = gsubbed_str[0..-3]
   upcased_str = spliced_str.upcase
end
</code>```

(Note that in Ruby the value of a method's last expression is the return value.)

答:
ok, in response to downvotes on my reasoning, I submit.

this is called using a Temp variable

And

it is bad

I definitely like the second snippet better.  With new variable names I know what is supposed to happening instead of having to guess about the intention of the original coder.  This makes it a thousands times easier to refactor  code, to simply add two lines in between two existing lines, or to create a whole function for what was a simple assignment or manipulation by a accumulation or something.

Managing complexity is critical to success of any non trivial program, and this 'technique' of using the same variable name is not helping manage complexity.  In fact, it is making it worse, as the code reader has to deal with a  kind of multipurpose, polymorphic variable.

The only case I can see this being somewhat helpful is when

The scope of this variable is very short and adding verbose names would only complicate things more.  But beware, what seems simple and of short scope now, can easily be expanded over time, and programmers won't rename anything and eventually you end up with a mess.

Sometimes, when you know the expected output format of a variable at the end of a function, you MAY use that variable as it's own temporary holding area for some manipulations that are relatively incidental and the whole scope of the variable remains small.  But even this, SO, SO, SO many times, when trying to redesign and refactor code like this, I'd would have rather the original coder spent twice as many lines and twice as many variables, just to show me exactly, in
explaining to 6-year old level of detail, what is supposed to be going on. Nonbelievers, flame on.


问:
Are too many if-else statements for validation bad?
From the book Professional Enterprise .Net, which has 5 star rating on Amazon that I am doubting after having a read through. Here is a Borrower class (In C# but it's pretty basic; anyone can understand it) that is part of a Mortgage application the authors built:

```<code>    public List<BrokenBusinessRule> GetBrokenRules()
    {
        List<BrokenBusinessRule> brokenRules = new List<BrokenBusinessRule>();

        if (Age < 18)
            brokenRules.Add(new BrokenBusinessRule("Age", "A borrower must be over 18 years of age"));

        if (String.IsNullOrEmpty(FirstName))
            brokenRules.Add(new BrokenBusinessRule("FirstName", "A borrower must have a first name"));

        if (String.IsNullOrEmpty(LastName))
            brokenRules.Add(new BrokenBusinessRule("LastName", "A borrower must have a last name"));

        if (CreditScore == null)
            brokenRules.Add(new BrokenBusinessRule("CreditScore", "A borrower must have a credit score"));
        else if (CreditScore.GetBrokenRules().Count > 0)
        {
            AddToBrokenRulesList(brokenRules, CreditScore.GetBrokenRules());
        }

        if (BankAccount == null)
            brokenRules.Add(new BrokenBusinessRule("BankAccount", "A borrower must have a bank account defined"));
        else if (BankAccount.GetBrokenRules().Count > 0)
        {
            AddToBrokenRulesList(brokenRules, BankAccount.GetBrokenRules());
        }
        // ... more rules here ...
        return brokenRules;
    }
</code>```

Full code listing on snipt.org .

What is confusing me is that the book is supposed to be about professional enterprise design. Maybe I am a bit biased because the author confesses in chapter 1 that he didn't genuinely know what decoupling was, or what SOLID meant until the 8th year of his programming career (and I think he wrote the book in  year 8.1)

I am no expert but I don't feel comfortable with:

Too many if else statements.

The class both serves as an entity and has validation. Isn't that a smelly design? (You might need to view the full class to get some context)

Maybe I am wrong, but I don't want to pick up bad practices from a book which is supposed to be teaching an enterprise design. The book is full of similar code snippets and it is really bugging me now. If it is bad design, how could you avoid using too many if else statements.

I obviously do not expect you to rewrite the class, just provide a general idea of what could be done.

答:
That's not reusable at all. I would use Data Annotations or similar attribute based validation framework. Check http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx for example.

Edit: my own example

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

namespace ValidationTest
{
    public interface ICategorized
    {
        [Required]
        string Category { get; set; }
    }
    public abstract class Page
    {
        [Required]
        [MaxLength(50)]
        public string Slug { get; set; }
        [Required]
        public string Title { get; set; }
        public string Text { get; set; }

        public virtual ICollection<ValidationResult> Validate()
        {
            var results = new List<ValidationResult>();
            ValidatePropertiesWithAttributes(results);
            ValidatePropertiesFromInterfaces(results);
            return results;
        }
        protected void ValidatePropertiesWithAttributes(ICollection<ValidationResult> results)
        {
            Validator.TryValidateObject(this, new ValidationContext(this,null,null), results);
        }
        protected void ValidatePropertiesFromInterfaces(ICollection<ValidationResult> results)
        {
            foreach(var iType in this.GetType().GetInterfaces())
            {
                foreach(var property in iType.GetProperties())
                {
                    foreach (var attr in property.GetCustomAttributes(false).OfType<ValidationAttribute>())
                    {
                        var value = property.GetValue(this);
                        var context = new ValidationContext(this, null, null) { MemberName = property.Name };
                        var result = attr.GetValidationResult(value, context);
                        if(result != null)
                        {
                            results.Add(result);
                        }
                    }
                }
            }
        }
    }
    public class Blog : Page
    {

    }
    public class Post : Page, ICategorized
    {
        [Required]
        public Blog Blog { get; set; }
        public string Category { get; set; }
        public override ICollection<ValidationResult> Validate()
        {
            var results = base.Validate();
            // do some custom validation
            return results;
        }
    }
}
</code>```

It's easy to modify to include/exclude properties ValidatePropertiesWithAttributes(string[] include, string[] exclude) or add rule provider to get rules from db Validate(IRuleProvider provider) etc.

Body:
That's not reusable at all. I would use Data Annotations or similar attribute based validation framework. Check http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx for example.

Edit: my own example

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace ValidationTest
{
    public interface ICategorized
    {
        [Required]
        string Category { get; set; }
    }
    public abstract class Page
    {
        [Required]
        [MaxLength(50)]
        public string Slug { get; set; }
        [Required]
        public string Title { get; set; }
        public string Text { get; set; }

        public virtual ICollection<ValidationResult> Validate()
        {
            var results = new List<ValidationResult>();
            ValidatePropertiesWithAttributes(results);
            ValidatePropertiesFromInterfaces(results);
            return results;
        }
        protected void ValidatePropertiesWithAttributes(ICollection<ValidationResult> results)
        {
            Validator.TryValidateObject(this, new ValidationContext(this,null,null), results);
        }
        protected void ValidatePropertiesFromInterfaces(ICollection<ValidationResult> results)
        {
            foreach(var iType in this.GetType().GetInterfaces())
            {
                foreach(var property in iType.GetProperties())
                {
                    foreach (var attr in property.GetCustomAttributes(false).OfType<ValidationAttribute>())
                    {
                        var value = property.GetValue(this);
                        var context = new ValidationContext(this, null, null) { MemberName = property.Name };
                        var result = attr.GetValidationResult(value, context);
                        if(result != null)
                        {
                            results.Add(result);
                        }
                    }
                }
            }
        }
    }
    public class Blog : Page
    {

    }
    public class Post : Page, ICategorized
    {
        [Required]
        public Blog Blog { get; set; }
        public string Category { get; set; }
        public override ICollection<ValidationResult> Validate()
        {
            var results = base.Validate();
            // do some custom validation
            return results;
        }
    }
}

It's easy to modify to include/exclude properties ValidatePropertiesWithAttributes(string[] include, string[] exclude) or add rule provider to get rules from db Validate(IRuleProvider provider) etc.


答:
Unless I'm missing something here, the word you're looking for is one you already have:  variable.

In mathematics, a variable is a value that may change within the scope of a given problem or set of operations.

With this technique:

```<code># uses diff vars
def cromulentize(str="")
    non_empty_str = str.empty? ? "wowza" : str
    adios_str = non_empty_str += " adios!"
    multiplied_str = adios_str * 3
    gsubbed_str = multiplied_str.gsub!('a', 'X')
    spliced_str = gsubbed_str[0..-3]
    upcased_str = spliced_str.upcase
end
</code>```

What you actually have there is a bunch of constants since their value is assigned once and never changed after that.

Title: Changing a variable through a series of statements ... What is this technique called?

Body:
I'm looking at a function that that has several statements like this:

```<code>n = returnDifferentVersionOf(n);
</code>```

I.e., the value of the same variable n changes progressively several times during the course of a subroutine -- rather than a newly named variable being assigned at each change.

What is the generic name of this technique (if there is one)?

A more full example might be (in Ruby):

```<code># reuse same var
def cromulentize(str="")
   str = "wowza" if str.empty?
   str += " adios!"
   str = str * 3
   str.gsub!('a', 'X')
   str = str[0..-3]
   str.upcase
end
</code>```

What is that technique called, as opposed to this one:

```<code># uses diff vars
def cromulentize(str="")
   non_empty_str = str.empty? ? "wowza" : str
   adios_str = non_empty_str += " adios!"
   multiplied_str = adios_str * 3
   gsubbed_str = multiplied_str.gsub!('a', 'X')
   spliced_str = gsubbed_str[0..-3]
   upcased_str = spliced_str.upcase
end
</code>```

(Note that in Ruby the value of a method's last expression is the return value.)

Body:
Unless I'm missing something here, the word you're looking for is one you already have:  variable.

In mathematics, a variable is a value that may change within the scope of a given problem or set of operations.

With this technique:

# uses diff vars
def cromulentize(str="")
    non_empty_str = str.empty? ? "wowza" : str
    adios_str = non_empty_str += " adios!"
    multiplied_str = adios_str * 3
    gsubbed_str = multiplied_str.gsub!('a', 'X')
    spliced_str = gsubbed_str[0..-3]
    upcased_str = spliced_str.upcase
end

What you actually have there is a bunch of constants since their value is assigned once and never changed after that.


答:
Managers are not interested in technical details, they are interested in efficiency.

To sell a new technology to managers, you have to convince them that this technology allows to produce a better product in less time with less money.

But are you sure that this is the case?

Can you prove that project X will be cheaper to develop when it is done in Scala instead of the language you are currently using? And how much time and money will it cost to find and/or train programmers to be proficient enough with Scala to benefit from the transition?

Before you bring up the topic, make sure that you have a good answer to these questions, and that you have independent references to back them.

Title: How to promote Scala to the management?


答:
Enh. Normally that sort of thing should be considered a code smell, but in this particular instance I think it's fine. Yes, you could look to do annotations but they're a pain and a half to debug. Yes, you could look to move the validation to a different class, but this sort of validation is unlikely to vary or be reused for other types.

This implementation is effective, easy to test, and easy to maintain. For many applications, this design will strike the right balance of design trade-offs. For others, more decoupling may be worth the extra engineering.

Title: Are too many if-else statements for validation bad?

Body:
From the book Professional Enterprise .Net, which has 5 star rating on Amazon that I am doubting after having a read through. Here is a Borrower class (In C# but it's pretty basic; anyone can understand it) that is part of a Mortgage application the authors built:

```<code>    public List<BrokenBusinessRule> GetBrokenRules()
    {
        List<BrokenBusinessRule> brokenRules = new List<BrokenBusinessRule>();

        if (Age < 18)
            brokenRules.Add(new BrokenBusinessRule("Age", "A borrower must be over 18 years of age"));

        if (String.IsNullOrEmpty(FirstName))
            brokenRules.Add(new BrokenBusinessRule("FirstName", "A borrower must have a first name"));

        if (String.IsNullOrEmpty(LastName))
            brokenRules.Add(new BrokenBusinessRule("LastName", "A borrower must have a last name"));

        if (CreditScore == null)
            brokenRules.Add(new BrokenBusinessRule("CreditScore", "A borrower must have a credit score"));
        else if (CreditScore.GetBrokenRules().Count > 0)
        {
            AddToBrokenRulesList(brokenRules, CreditScore.GetBrokenRules());
        }

        if (BankAccount == null)
            brokenRules.Add(new BrokenBusinessRule("BankAccount", "A borrower must have a bank account defined"));
        else if (BankAccount.GetBrokenRules().Count > 0)
        {
            AddToBrokenRulesList(brokenRules, BankAccount.GetBrokenRules());
        }
        // ... more rules here ...
        return brokenRules;
    }
</code>```

Full code listing on snipt.org .

What is confusing me is that the book is supposed to be about professional enterprise design. Maybe I am a bit biased because the author confesses in chapter 1 that he didn't genuinely know what decoupling was, or what SOLID meant until the 8th year of his programming career (and I think he wrote the book in  year 8.1)

I am no expert but I don't feel comfortable with:

Too many if else statements.

The class both serves as an entity and has validation. Isn't that a smelly design? (You might need to view the full class to get some context)

Maybe I am wrong, but I don't want to pick up bad practices from a book which is supposed to be teaching an enterprise design. The book is full of similar code snippets and it is really bugging me now. If it is bad design, how could you avoid using too many if else statements.

I obviously do not expect you to rewrite the class, just provide a general idea of what could be done.


答:
One more thing concerning point 2 of your question: removing the validation logic from that class (or any other logic which does not serve the purpose of the class beeing an entity) removes the business logic completely. This leaves you with an anemic domain model, which is mostly considered to be an anti-pattern.

EDIT: Of course, I agree fully to Eric Lippert that specific business logic which is likely to be changed often should not be hardcoded into the object. That still does not mean that it is a good design to remove any business logic from business objects, but this particular validiation code is a good candidate for beeing extracted to a place where it can be changed from outside.


答:
Yes, this is a bad smell, but the solution is easy.  You have a BrokenRules list, but all a BrokenBusinessRule is, as far as I can see, is a name and an explanatory string.  You have this upside down.  Here's one way to do it (please note: this is off the top of my head and didn't involve much design thought - I'm sure something better could be done with more thought):

Create a BusinessRule class and a RuleCheckResult class.

Give it a name property, a "checkBorrower" method that returns a RuleCheckResult class.

Do whatever is necessary to allow BusinessRule to see all the checkable  properties of Borrower (make it an inner class, for example).

Create subclasses for each specific type of rule (or, better, use anonymous inner classes or a rule factory or a sane language that supports closures and higher order functions).

Populate a collection with all the rules you actually want to use

Then all of those if-then-else statements can be replaced by a simple loop something like this:

```<code>for (BusinessRule rule: businessRules) {
  RuleCheckResult result = rule.check(borrower);
  if (!result.passed) {
    for (RuleFailureReason reason: result.getReasons()) {
      BrokenRules.add(rule.getName(), reason.getExplanation())
    }
}
</code>```

Or you could make it simpler and just have this

```<code>for (BusinessRule rule: businessRules) {
  RuleCheckResult result = rule.check(borrower);
  if (!result.passed) {
      BrokenRules.add(rule.getName(), result)
    }
}
</code>```

It should be pretty obvious how RuleCheckResult and RuleFailureReason might be composed.

Now you can have complex rules with multiple criteria or simple rules with none.  But you're not trying to represent all of those in one long set of ifs and if-elses and you don't have to rewrite the Borrower object each time you come up with a new rule or drop an old one.

Body:
Yes, this is a bad smell, but the solution is easy.  You have a BrokenRules list, but all a BrokenBusinessRule is, as far as I can see, is a name and an explanatory string.  You have this upside down.  Here's one way to do it (please note: this is off the top of my head and didn't involve much design thought - I'm sure something better could be done with more thought):

Create a BusinessRule class and a RuleCheckResult class.

Give it a name property, a "checkBorrower" method that returns a RuleCheckResult class.

Do whatever is necessary to allow BusinessRule to see all the checkable  properties of Borrower (make it an inner class, for example).

Create subclasses for each specific type of rule (or, better, use anonymous inner classes or a rule factory or a sane language that supports closures and higher order functions).

Populate a collection with all the rules you actually want to use

Then all of those if-then-else statements can be replaced by a simple loop something like this:

for (BusinessRule rule: businessRules) {
  RuleCheckResult result = rule.check(borrower);
  if (!result.passed) {
    for (RuleFailureReason reason: result.getReasons()) {
      BrokenRules.add(rule.getName(), reason.getExplanation())
    }
}

Or you could make it simpler and just have this

for (BusinessRule rule: businessRules) {
  RuleCheckResult result = rule.check(borrower);
  if (!result.passed) {
      BrokenRules.add(rule.getName(), result)
    }
}

It should be pretty obvious how RuleCheckResult and RuleFailureReason might be composed.

Now you can have complex rules with multiple criteria or simple rules with none.  But you're not trying to represent all of those in one long set of ifs and if-elses and you don't have to rewrite the Borrower object each time you come up with a new rule or drop an old one.


答:
I'm a .NET developer, so I wrote this in notepad using C# syntax (which might be identical to JAVA).

```<code>public class BorrowerValidator
{
    private readonly Borrower _borrower;

    public BorrowerValidator(Borrower borrower)
    {
        _borrower = borrower;
        Validate();
    }

    private readonly IList<ValidationResult> _validationResults;

    public IList<ValidationResult> Results
    {
        get
        {
            return _validationResults;
        }
    }

    private void Validate()
    {
        ValidateAge();
        ValidateFirstName();
        // Carry on
    }

    private void ValidateAge()
    {
        if (_borrower.Age < 18)
            _validationResults.Add(new ValidationResult("Age", "Borrower must be over 18 years of age");
    }

    private void ValidateFirstname()
    {
        if (String.IsNUllOrEmpty(_borrower.Firstname))
            _validationResults.Add(new ValidationResult("Firstname", "A borrower must have a first name");
    }
}

Usage:

var borrower = new Borrower
{
    Age = 17,
    Firstname = String.Empty
};

var validationResults = new BorrowerValidator(borrower).Results;
</code>```

There is no point in passing borrower object to ValidateAge and ValidateFirstName, instead, just store it as a field.

To take things further, you can extract an interface: IBorrowerValidator. Say you then have different ways to validate your borrowers depending on their financial circumstances. For example, if somebody is ex-bankrupt, you may have:

```<code>public class ExBankruptBorrowerValidator : IBorrowerValidator
{
   // Much stricter validation criteria
}
</code>```

Body:
I'm a .NET developer, so I wrote this in notepad using C# syntax (which might be identical to JAVA).

public class BorrowerValidator
{
    private readonly Borrower _borrower;

    public BorrowerValidator(Borrower borrower)
    {
        _borrower = borrower;
        Validate();
    }

    private readonly IList<ValidationResult> _validationResults;

    public IList<ValidationResult> Results
    {
        get
        {
            return _validationResults;
        }
    }

    private void Validate()
    {
        ValidateAge();
        ValidateFirstName();
        // Carry on
    }

    private void ValidateAge()
    {
        if (_borrower.Age < 18)
            _validationResults.Add(new ValidationResult("Age", "Borrower must be over 18 years of age");
    }

    private void ValidateFirstname()
    {
        if (String.IsNUllOrEmpty(_borrower.Firstname))
            _validationResults.Add(new ValidationResult("Firstname", "A borrower must have a first name");
    }
}

Usage:

var borrower = new Borrower
{
    Age = 17,
    Firstname = String.Empty
};

var validationResults = new BorrowerValidator(borrower).Results;

There is no point in passing borrower object to ValidateAge and ValidateFirstName, instead, just store it as a field.

To take things further, you can extract an interface: IBorrowerValidator. Say you then have different ways to validate your borrowers depending on their financial circumstances. For example, if somebody is ex-bankrupt, you may have:

public class ExBankruptBorrowerValidator : IBorrowerValidator
{
   // Much stricter validation criteria
}


答: In the main class of the program I would pass the Borrower entity into the BrokenBusinessRule class and do the business logic there to simplify testing and readability some more (Note: If this were a larger more complicated program the importance of decoupling would be much greater)


答:
Magnetic storage is slow, so better put a cache in front of it.  It's easy to see how that accelerates reads, but can it accelerate writes too?

a writethrought cache doesn't, because although it keeps a copy of the written data in the cache (for subsequent reads), it doesn't acknowledge the operation as successful until it's on real storage ("hits iron oxide").

a writeback cache does, because it signals the host that the opration is finished as soon as it is on cache.  It will write to permanent (magnetic) storage somewhat later, in the background.

At first, writeback caches sound better, but they introduces a vulnerability window: if there's a power loss, any data acknowledged but not yet written would be lost.  The filesystems or databases can't prevent this, because any journalling, scheduler barriers, operation ordering, etc. depend on the write acknowledge to mean that data is already safely written.

The solution is to add a small battery to the cache, to allow it to survive a power loss.  As soon as power is restored, any pending writes will be completed (even before the host is booted up).

Now there are also two other alternatives:

replace the RAM cache with non-volatile storage.  SSD's can be much bigger for the same cost, but they're not as fast as RAM.  Still, in many cases they're faster than the data link, so they can be fast enough.

add a small non-volatile memory to the cache.  In the event of power loss, a very small battery (or a supercapacitor) allows it just enough extra time to save the pending cache entries to flash.  No need to keep RAM alive for an indeterminate amount of hours.

Title: What is a battery backup up cache?


问:
Example(s) of "A subscript ([ ]) expression that does not evaluate to an array" in C
I think I have never seen a [] that doesn't mean array in C.

Background:

I was reading about l-values and r-values here: http://msdn.microsoft.com/en-us/library/bkbs2cds.aspx and there it says so. I am curious.

答:
What it says there is "A subscript ([ ]) expression that does not evaluate to an array."  The key words here are "evaluate to."

If you have an array of int called x, the expression x[5] evaluates to an int, not an array.  On the other hand, if it's an array of arrays of int, the expression x[5] evaluates to an array of int, and therefore is can't be a valid l-value.


答:
The closest name you could really give this is "'threading' (not in the concurrent programming sense) or 'compose' in an imperative language". This is exactly the sort of thing that (eg) Clojure solves with its -> macro.

http://blog.fogus.me/2009/09/04/understanding-the-clojure-macro/

It takes a series of functions that should be executed in a particular order and feeds the result of each function to the next function in the sequence. You could achieve the same effect by simply nesting function calls but that gets ugly fast.


问:
Sql Server Data Tools & Entity Framework - is there any synergy here?
Coming out of a project using Linq2Sql, I suspect that the next (bigger) one might push me into the arms of Entity Framework. I've done some reading-up on the subject, but what I haven't managed to find is a coherent story about how SQL Server Data Tools and Entity Framework should/could/might be used together.

Were they conceived totally separately, and using them together is stroking the wrong way?

Are they somehow totally orthogonal and I'm missing the point?

Some reasons why I think I might want both:

SSDT is great for having 'compiled' (checked) and easily versionable sql and schema

But the SSDT 'migration/update' story is not convincing (to me): "Update anything" works ok for schema, but there's no way (AFAIK) that it can ever work for data.

On the other hand, I haven't tried the EF migration to know if it presents similar problems, but the Up/Down bits look quite handy.

答:
There is more than one way to use EF with a SQL Server database.

Code-First... You write classes, and EF generates the associated tables

Database First ... You design the tables, and EF generates the classes.

EF will not necessarily do all of the work for you.  EF will get you about 80 to 95 percent there.  The other 5 to 20 percent of your database development effort will be supplemented with optimizations like Views and Stored Procedures.

So no, they are not orthogonal.  But you'll have to decide what your overall design strategy will be, and then rely on tools like SSDT to help you optimize those parts where EF produces less than ideal results.


答:
Given your starting point the solution is pretty straight forward. Assume that you start with all times being available so your initial display will be:

Jan 1st 12:00am - Dec 31st 11:59pm

Assuming that the appointment times are in chronological order and there is no overlap with any of them (if not, you should be able to make an algorithm to fix up the list for you) the solution is simple.

For each "unavailable" slot:

Take the last available slot and split it into two

set the start time of the first slot to the start time of the original

set the end time of the first slot to the start time of the "unavailable" slot

set the start time of the second slot to the end time of the "unavailable" slot

set the end time of the second slot to the end time of the original.

Once you've down that you'll have a list of available slots. Here's an example:

Original availability is Jan 1st 12:00 AM - Dec 31st 11:59 PM

you have the following "unavailable" slots

Jan 15th 12:00 AM - Jan 15th 11:59 PM

Jan 20th 12:00 PM - Feb 4th 9:00 AM

Feb 14th 1:00 PM - Feb 14th 5:00 PM

The first run of the algorithm would look like so

Original Jan 1st 12:00 AM - Dec 31st 11:59 PM

Split into two

First runs Start of original to start of "unavailable"

Jan 1st 12:00 AM - Jan 15th 12:00 AM

Second runs End of "unavailable" to end of original

Jan 15th 11:59 PM - Dec 31st 11:59 PM

So now you have two available slots

Jan 1st 12:00 AM - Jan 15th 12:00 AM

Jan 15th 11:59 PM - Dec 31st 11:59 PM

Do the same operations with the next two and you're home free.

Don't forget edge cases.

What happens when you have an available slot that is essential zero in length?
What happens when one of the "unavailable slots runs past the end or before the beginning of your window?

Title: C# Logic - gaps & Islands

Body:
I am looking for help designing the display of available times for appointments (for example a hairdresser's appointment book).

Currently I have a query that returns a collection of periods that are unavailable for appointments (whether there is an existing appointment or if the service provider is closed).

So lets say Feb 3rd, from 12 to 5 is unavailable, i want to output the following string:
Jan 1st 12 am - Feb 3rd 12pm
Feb 3rd, 5pm - Dec 31 12 am.

My entire range is 1 year from Jan 1st to December 31st and there can be as many unavailable dates.


答:
I am no expert but I don't feel comfortable with

1- Too many if else statements.

2- The class both serves as an entity, AND has validation. Isn't that a smelly design?

Your intuition is spot on here. This is a weak design.

The code is intended to be a business rule validator. Now imagine that you work for a bank and the policy is changed from having to be 18, to having to be 21, but if there is an approved co-signer then having an 18 year old is allowed, unless the co-signer lives in Maryland, in which case...

You see where I'm going here.  Rules change all the time in banks and rules have complex relationships with each other. Therefore this code is a bad design because it requires a programmer to rewrite the code every time a policy changes.  The intention of the given code is to produce a reason why a policy has been violated, and that's great, but in that case policies should be objects, not if statements, and policies should be loaded in from a database, not hard-coded into the validation for construction of an object.


答:
Start with your team, not your managers.  "Our whole team want to use this" is something any manager will pay attention to, even if they ultimately disagree.  Do not, in contrast, attempt to use your managers to impose an unpopular choice on your team.  Even if it works, your professional life will not be worth living.

Write something useful in Scala on your own time (by which I don't necessarily mean at home, out of office hours - I mean without compromising delivery of your set objectives).  Show how Scala made it easier.  Show how Scala makes it easier for others to extend your work.  This will be particularly useful if your team needs convincing (see above).

Do some research about the maintenance implications for the rest of your organisation.  How will this affect testers, application support, release management, continuous integration and so on?  You need to find real answers to this.  If your workplace already supports the JVM (i.e. Java/Groovy), this will be much easier but there will still be an impact beyond your immediate team.

Be prepared to accept no for an answer.

If you fail in the short term, go back to step 1 above.  Try and get your regular dev colleagues interested in Scala.  If enough of them get the itch, they may make the case for you.

Title: How to promote Scala to the management?


问:
Is it a good idea to use a kitchen-sink server for various services?
My (new) development team is setting up its software development environment. I won't describe the whole scenario, since that's another, much-maligned question.

Anyway, we're going to have services such as source control (mercurial), a wiki, an issue tracker, a file/document server, DNS and possibly other things. My question: Is it a good idea to put as many as possible as these on a single 'kitchen-sink' server machine? Or is it better to spread them out as much as money, power and server room space allows?

Notes:

I know that some things have to go on a different server, like continuous/periodic building, with a lot of crunching involved. I'm talking about the (theoretically) lighter stuff.

Our team has 4 people, expected to grow to maybe double that within the next couple of years.

We're not going to be 'hammering' services, as far as I can tell.

The expected hardware for the server is a plain vanilla PC, ~ $1,000 at most, maybe with an SSD.

答:
In my opinion it heavily depends on your resource consumption. If one server is overloaded it may cause problems. So if you have a small team I don't see many problems.

If you want to be able to scale this infrastructure it is maybe better to keep things separated.

If you are has me, a guy that like the beauty of the big car and engines, you might have fun having a beautiful and powerfull setup.


答:
I think that in these types of rules scenarios, a good pattern to apply is The Specification Pattern.  It not only creates a more elegant way to encapsulate an individual business rule, it also does it in a way so that the individual rule can be combined with other rules to build more complex rules.  All without (IMHO) requiring an over-engineered infrastructure.  The Wikipedia page also provides a pretty awesome C# implementation that you can use right out of the box (although with anything I recommend understanding it and not just blindly pasting it).

To use a modified example from the Wikipedia page:

```<code>ValidAgeSpecification IsOverEighteen = new ValidAgeSpecification();
HasBankAccountSpecification HasBankAccount = new HasBankAccountSpecification();
HasValidCreditScoreSpecification HasValidCreditScore = new HasValidCreditScoreSpecification();

// example of specification pattern logic chaining
ISpecification IsValidBorrower = IsValidAge.And(HasBankAccount).And(HasValidCreditScore);

BorrowerCollection = Service.GetBorrowers();

foreach (Borrower borrower in BorrowerCollection ) {
    if (!IsValidBorrower.IsSatisfiedBy(borrower))  {
        validationMessages.Add("This Borrower is not Valid!");
    }
}
</code>```

You may say "This particular example doesn't list the individual rules being broken!".  The point here is to demonstrate how rules can be composed.   You can just as easily move all 4 rules (including the composite one) into a collection of ISpecification and iterate over them like itsbruce has demonstrated.

Later on, when the higher ups want to make a new loan program that's only available to teenagers which have a cosigner, creating a rule like that is easy and more declarative.  Plus you can reuse your existing age rule!

ISpecification ValidUnderageBorrower = IsOverEighteen.Not().And(HasCosigner);

Body:
I think that in these types of rules scenarios, a good pattern to apply is The Specification Pattern.  It not only creates a more elegant way to encapsulate an individual business rule, it also does it in a way so that the individual rule can be combined with other rules to build more complex rules.  All without (IMHO) requiring an over-engineered infrastructure.  The Wikipedia page also provides a pretty awesome C# implementation that you can use right out of the box (although with anything I recommend understanding it and not just blindly pasting it).

To use a modified example from the Wikipedia page:

ValidAgeSpecification IsOverEighteen = new ValidAgeSpecification();
HasBankAccountSpecification HasBankAccount = new HasBankAccountSpecification();
HasValidCreditScoreSpecification HasValidCreditScore = new HasValidCreditScoreSpecification();

// example of specification pattern logic chaining
ISpecification IsValidBorrower = IsValidAge.And(HasBankAccount).And(HasValidCreditScore);

BorrowerCollection = Service.GetBorrowers();

foreach (Borrower borrower in BorrowerCollection ) {
    if (!IsValidBorrower.IsSatisfiedBy(borrower))  {
        validationMessages.Add("This Borrower is not Valid!");
    }
}

You may say "This particular example doesn't list the individual rules being broken!".  The point here is to demonstrate how rules can be composed.   You can just as easily move all 4 rules (including the composite one) into a collection of ISpecification and iterate over them like itsbruce has demonstrated.

Later on, when the higher ups want to make a new loan program that's only available to teenagers which have a cosigner, creating a rule like that is easy and more declarative.  Plus you can reuse your existing age rule!

ISpecification ValidUnderageBorrower = IsOverEighteen.Not().And(HasCosigner);


问:
Multiple Dispatch and CLOS
I have never written software in Common Lisp, but in Scheme and Clojure as well as C++ and Python. Yet I have had a look at the Common Lisp Object System (CLOS) in Common Lisp and Dylan. Now when comparing it to OOP in the Simula tradition, CLOS and lets say C++ and Python class system have polymorphism as a common trait.

They seem to differ in the way how data and methods are organized, in the Simula family, methods are an integral part of classes, sub-items if you will while with CLOS they are defined outside of classes and are rather generalized procedures.

Common Lisp proponents typically argue that virtual methods in Simula-family programming languages are quite limited since they are invoked only according to the first-argument object (this or self). CLOS generic functions are selected for several arguments, thus something like (pseudo code)

```<code>method draw(c : Device, d : Drawable) ...
</code>```

can be implemented for arbitrary Canvas and Drawable combinations.

```<code>method draw(c : Printer, t : Triangle)....
method draw(c : Printer, t : Image)....
method draw(c : Screen, t : Image) ....
</code>```

In Simula-family languages, this would be more difficult, since draw would have to be associated with either the Device or the Drawable family of objects. The canonical solution seems to be the Visitor Pattern http://en.wikipedia.org/wiki/Visitor_Pattern .

Upon learning CLOS, I was quite amazed that most OO programming languages do not offer multiple dispatch - and - wondered if there are specific reasons, why one might associate methods so closely with one specific class. Are there specific advantages for single dispatch?

ambiguity of multiple dispatch: i.e. lets say I have a subclassing A and b subclassing B. The method foo(A,B) implemented as foo(a,B) and foo(A,b), which implementation would a call of  foo(a,b) invoke? Is this the only reason?

"Modularizing", methods in the class are near.

Is there more to it? Have language designers and creators taken a stance on this matter?

答: Beyond "modularity", a consequence of a method associated (or belonging) to an object is its autonomy to chose how to respond to a message (and to "travel" with its own behavior). With multi dispatch as found in these languages, you have an underlying global mechanism doing the binding and deciding how computation is carried out.</p>

Title: Multiple Dispatch and CLOS


问:
Architecting Domain Layer and other modules with dependency injection in mind
I am currently new to Dependency Injection pattern. I am influenced by link by Mark Seemann.

I have a confusion regarding whether an interface for an agent class of some agent module should be included in domain layer?
by agent I mean a class / module that interacts with external wcf/ webservices.

I have a diagram that shows it.
In short, is it Ok to have:

IProductAgent interface in Business layer where the actual implementation will be in an Agent Module.

The confusion arises by the fact that:  Is calling a service even considered a business rule?

Today a service fulfills a facility, tomorrow there might be some another means of catering this same facility. Liskov's Substitution Principle.

Apologies if I am mixing things here.

答:
Yes, the domain layer may have external dependencies where the dependencies are defined by interfaces. Taking this approach makes the domain layer ignorant of the actual implementation

Erik Evans who defined Domain Driven Design does in fact use this approach in his book to be able to load domain entities from a data source.


问:
Is fixing bugs made by other people a good approach?
Let's assume the situation where a team of four developers is building an application. During the testing phase, bugs are reported by users. Who should fix them? The person who committed the erroneous code, or anyone who is free?

What is preferred approach in agile development (scrum)?

答: In my team, we always decide according to priority. if the person who submitted the code is available, he/she fixes the code. If that person is working on some higher priority story, anyone who is available and can fix the code as soon as possible will fix it. If everyone is busy with working on higher priority tasks in the current iteration, the fix is scheduled in the next iteration according to its priority as compared to the other stories and defects.</p>


问:
So what *did* Alan Kay really mean by the term "object-oriented"?
Reportedly, Alan Kay is the inventor of the term "object oriented". And he is often quoted as having said that what we call OO today is not what he meant.

For example, I just found this on Google:

I made up the term 'object-oriented', and I can tell you I didn't have C++ in mind

-- Alan Kay, OOPSLA '97

I vaguely remember hearing something pretty insightful about what he did mean. Something along the lines of "message passing".

Do you know what he meant? Can you fill in more details of what he meant and how it differs from today's common OO? Please share some references if you have any.

答:
Most if not all of what Alan Kay meant by object-orientation is embodied in the Smalltalk language.

"We didn’t even do all of the idea at PARC. Many of Carl Hewitt’s Actors ideas which got sparked by the original Smalltalk were more in the spirit of OOP than the subsequent Smalltalks. Significant parts of Erlang are more like a real OOP language the the current Smalltalk, and certainly the C based languages that have been painted with “OOP paint”."

Taken from Alan Kay's comment at:

http://computinged.wordpress.com/2010/09/11/moti-asks-objects-never-well-hardly-ever/

OwnerDisplayName: Charlie Flowers


答:
TL;DR

Is it a good idea to use a kitchen-sink server for various services?

There's no universally-correct answer to this question. It is fundamentally a business decision based on the budget you have and the problems you are trying to solve for.

Arguments for Separating Services

There are many reasons for separating services, but two of the biggest reasons for separating services are:

Service isolation.

Ensure so that system failures, resource exhaustion, or security flaws related to one service don't take down all the others. Also good for enforcing a separation of duties at the system level.

Capacity planning.

Ensure that services aren't contending for limited resources such as disk I/O, memory, or CPU.

Arguments for Combining Services

Putting multiple services on a single host or cluster has some advantages, too. Some specific examples include:

A potential reduction in equipment costs.

A lot of this depends on whether you have to scale up as an alternative to scaling out. If not, then fewer machines is generally cheaper.

Lower administrative burden.

Fewer machines to manage can simplify administrative tasks and reduce administrative costs.

Summary

It's not all-or-nothing. You can do a lot to isolate services and manage resource consumption on a single box, and you can also use tools and work-flows to reduce costs and administrative burden as you scale out.

Determining what your team needs and what you hope to get out of your design choices is generally the right first step. The critical thing is to ensure that everyone in the organization is on the same sheet of music about whatever decisions are made.

Body:
My (new) development team is setting up its software development environment. I won't describe the whole scenario, since that's another, much-maligned question.

Anyway, we're going to have services such as source control (mercurial), a wiki, an issue tracker, a file/document server, DNS and possibly other things. My question: Is it a good idea to put as many as possible as these on a single 'kitchen-sink' server machine? Or is it better to spread them out as much as money, power and server room space allows?

Notes:

I know that some things have to go on a different server, like continuous/periodic building, with a lot of crunching involved. I'm talking about the (theoretically) lighter stuff.

Our team has 4 people, expected to grow to maybe double that within the next couple of years.

We're not going to be 'hammering' services, as far as I can tell.

The expected hardware for the server is a plain vanilla PC, ~ $1,000 at most, maybe with an SSD.


问:
Open source development life cycle
I am working as a IT-developer. I am developing J2EE application in our own life project cycle methodology.

I have seen and learnt so many SDLC cycle models in order to develop a project but this open source development and its process still unknown to me.

So, how this open source development life cycle happen? How this life bring a powerfull products like Hibernate, Spring , Struts etc...

How can i contribute as a developer in these popular frameworks.?

答:
Open vs close source doesn't necessarily dictate anything when it comes to the development process. So... pick whatever floats your boat. Or get used to whatever the particular project is using. </p>

<p>Or don't. You can buck their process and fork your own build with your own process. That's how Ubuntu came to be. A group was miffed at Debian's long release cycle. </p>

Title: Open source development life cycle

Body:
Open vs close source doesn't necessarily dictate anything when it comes to the development process. So... pick whatever floats your boat. Or get used to whatever the particular project is using.

Or don't. You can buck their process and fork your own build with your own process. That's how Ubuntu came to be. A group was miffed at Debian's long release cycle.


问:
Logic design question for SQL query
Was wondering if you could help me on a SQL problem I’m having.

I have a set of records of events where each event has a start time and end time. No event has the same start time, and the end time for each event is greater than or equal to the preceding event.

What I want to be able to do is pull out the set of records that are not overlapping – where the start time for an event is not between the start/end for any other event.  In the example below, the start time for B/C/D are in-between A’s start and end, so I want to keep A, and get rid of B,C,D.  Then start over again, keeping E, and get rid of F, then start over and keep G, getting rid of H/I, etc.

Seems like this requires a self join but I can’t figure out the criteria for that would identify the records this way.  Any ideas?

```<code>Event |  Start  | End
A             1            10 (keep)
B             2            11 (discard because start time of 2 < 10)
C             5            15 (discard because start time of 5 < 10)
D             9            12 (discard because start time of 9 < 10)
E             10           13 (keep -  this starts a new set because it’s the first record after A with start >= A end)
F             11           20 (discard because 11 < 13)
G             14           22 (keep -  this starts a new set because it’s the first record after E with start >= E)
H             15           22 (discard because 15 < 22)
I             17           27 (discard because 17 < 22)
J             22           27 (keep -  this starts a new set because it’s the first record after G with start >= G)
</code>```

答:
Something like this is very easy in a stored procedure where you loop through the records, but very hard in plain SQL, because conceptually in SQL the records do not know anything about eachother.
So just loop through the records and discard those that you don't need.</p>

Title: Logic design question for SQL query


问:
Good, simple reasons for having multiple environments
Throughout my career I had worked at companies that had a collection of different environments for different purposes. We always had more or less our desktop environment, a test environment, a QA environment, a staging environment and a production environment. This went for both servers/applications and any data sources we were using.

When I started at my current company I found that 90% of the apps were either developed on a desktop environment against production data sources or developed directly on the production server depending on the platform. This wasn't particularly surprising, as I was hired in part to make changes to improve the way the development team functioned, which was clear from my interview process. We slowly started to turn the philosophy and pretty soon, most of the apps could be run in either a desktop, test or production environment. Not too long after that staging came around as well.

Now most of our developers see the benefit of this methodology and defend it vigilantly. However, we have a number of legacy apps that never got migrated. We also have a number of legacy programmers who think of this as a waste of time. Unfortunately, we got lip service but never full buy-in from management. We got what we thought was a commitment to invest substantially in this about a year ago, but nothing materialized despite the considerable planning that we put into it. Now we are finding that we need more and more environments. We need help from the server/network administration teams for setup and we need participation from the business stakeholders to support the release cycle. We are at a place now where a project can function what reasonable developers would consider "normally" only if you have the right people on the project and the time to set up the proper environments.

I'd love to present a complete argument, but management really has no time and interest in hearing me out until there is a critical issue. I can't really articulate the benefits simply as it always just seemed second nature to me. I was wondering if there are any good, simple, irrefutable reasons for the separation of environments that would get managers lacking development experience to support this idea?. Are there any good resources/literature on the topic?

答:
When it comes to making a change, you will be lucky to have someone who will just listen to your professional opinion and implement suggested changes.

On my experience, each time I had to make a major change, I had to justify it in terms of savings the business will make. For example, introducing ReSharper into the development pipeline was pretty easy, as I was able to say something on the lines off:

ReSharper costs around £50 per developer. Average developer cost per year is £40k. ReSharper should increase developers productivity by at least 20% given its used to its full potential. Say developer spends 75% of their time actually writing code in IDE. 75% of 40k is £30k. £30k is now the cost of developer's productivity. An additional percent of productivity (1%) per year costs £300. To get additional 20% productivity, the business would have to spend £6k.

If you were to put this into perspective to the business, you can say that you can hire somebody else and get additional 20% productivity for £6k, or you can get the same result by spending £50 on a ReSharper license. Once the figures are in front of the business, the decision will be easy to make.

Now in regards to your questions with having multiple environments, all you have to do is find a way of calculating how much it costs the business every year to now have these environments.

You can ask your fellow developers to keep track of hours spent each week on configuring applications for development, deployment etc. For example, ten hours of senior developer's time might cost business £500. That's 10 hours that can be spent on development, or something much more important. You gather the figures for some period of time and provide business with a yearly cost.

I personally hate this kind of politics, but it's common and we have to live with it.


问:
Java Program That Notifies When Camera is Being Accessed
I'm trying to find a developer to write me a pretty basic program. I am also a developer, but don't have enough time to write it myself.

This program has a pretty basic function. It will notify users, via some dialog (or alert) that some program is about to access the built in desktop / laptop camera. It could be skype or facetime, or whatever it is, the program should be aware of when the OS's camera is going to be accessed and notify the user. Yes, even if the user is initiating the camera themselves via Skype, the notification would still appear.

My question is this. If I need this program written in Java, is it possible? Obviously I am trying to get it done in Java so it would run on Windows and Mac.

If it is not possible, then it seems as though I'd have to write 2 separate programs on Windows and Mac.

I've come here to get suggestions so that I can connect with the right developers. If you have any suggestions, I'd be happy to hear them. Thanks!

答:
No, it isn't possible to write an application that detects if the camera is being accessed in Java.

The reason for this is that the "is accessing a usb device that happens to be camera" is something that is part of the deep system calls of the operating system.  To interrogate the system at this level, you need to be able to call methods against the system and hardware itself - something that java specifically abstracts away from you.

You might be able to write drivers for various cameras and access them in java, though each camera may require a different driver, and the driver for Windows is different than the driver for Mac.

You really need to abandon the requirement and idea that you will have a single application that works on both systems.  You will need to write a native application that is able to talk to the operating system and ask it about what devices it has and what their status is.  This isn't something Java was designed for.


问:
Blurring the lines between async and regular functions in C# 5.0
Lately I can't seem to get enough of the amazing async-await pattern of C# 5.0. Where have you been all my life?

I'm absolutely thrilled with the simple syntax, but I'm having one small difficulty. My problem is that async functions have a totally different declaration from regular functions. Since only async functions can await on other async functions, when I'm trying to port some old blocking code to async, I'm having a domino effect of functions I have to convert.

People have been referring to this as a zombie infestation. When async gets a bite in your code, it will keep getting bigger and bigger. The porting process is not difficult, it's just throwing async in the declaration and wrapping the return value with Task<>. But it is annoying to do this over and over again when porting old synchronous code.

It seems to me it will be much more natural if both function types (async and plain old sync) had the exact same syntax. If this were the case, porting will take zero effort and I could switch painlessly between the two forms.

I think this could work if we follow these rules:

Async functions won't require the async declaration anymore. Their return types wouldn't have to be wrapped in Task<>. The compiler will identify an async function during compilation by itself and do the Task<> wrapping automatically as needed.

No more fire-and-forget calls to async functions. If you want to call an async function, you will need to await on it. I hardly use fire-and-forget anyways, and all the examples of crazy race conditions or deadlocks always seem to be based on them. I think they are too confusing and "out of touch" with the synchronous mindset we try to leverage.

If you really can't live without fire-and-forget, there will be special syntax for it. In any case, it won't be part of the simple unified syntax I'm talking about.

The only keyword you need to denote an asynchronous call is await. If you have await, the call is asynchronous. If you don't, the call is plain old synchronous (remember, we don't have fire-and-forget anymore).

The compiler will identify async functions automatically (since they don't have a special declaration anymore). Rule 4 makes this very simple to do - if a function has an await call inside, it is async.

Could this work? or am I missing something? This unified syntax is much more fluid and could solve the zombie infestation altogether.

Some Examples:

```<code>// assume this is an async function (has await calls inside)
int CalcRemoteBalanceAsync() { ... }

// assume this is a regular sync function (has no await calls inside)
int CalcRemoteBalance() { ... }

// now let's try all combinations and see what they do:

// this is the common synchronous case - it will block
int b1 = CalcRemoteBalance();

// this is the common asynchronous case - it will not block
int b2 = await CalcRemoteBalanceAsync();

// choosing to call an asynchronous function in a synchronous manner - it will block
// this syntax was used previously for async fire-and-forget, but now it's just synchronous
int b3 = CalcRemoteBalanceAsync();

// strange combination - it will block since it's calling a synchronous function
// it should probably show a compilation warning though
int b4 = await CalcRemoteBalance();
</code>```

Note: this is a continuation of an interesting related discussion in SO

答:
Your question is already answered in the SO question you linked.

The purpose of async/await is to make it easier to write code in a
  world with many high latency operations. The vast majority of your
  operations are not high latency.

When WinRT first came out, the designers were describing how they decided which operations were going to be async.  They decided that anything that was going to take 50ms or more would be async, and the remainder of the methods would be ordinary, non-asynchronous methods.

How many of the methods had to be rewritten to make them asynchronous?  About 10 percent of them.  The other 90% were not affected at all.

Eric Lippert goes on to explain in fairly substantial technical detail why they opted not to take a one-size-fits-all approach.  He basically says that async and await are a partial implementation of continuation-passing style, and that optimizing such a style to fit all cases is a hard problem.


问:
Is there a tool that visually represents all the potential paths to a particular piece of code?
As an example of what I need and why I want it, I am trying to determine how a certain value (CurTotal) is getting set (wrongly). I've come up with these notes to myself to try to understand just what is happening:

**CurTotal is declared in frmEntry.SetTotalControlsProperties().

CurTotal gets its value within that method from wrkFile.getAmount(), and txtCurTot is eventually assigned that value.

SetTotalControlsProperties() is called:**

```<code>0) From the main (frmCentral) form's openfrmUPC() method
1) From frmEntry's overloaded constructor: public frmEntry(string DSDtablename, string recType, int QOne, int sDesc, int sList)
2) Conditionally from within DoSave(), which is called from btnSave_Click() and PrepareForPrinting()
3) From frmEntry's saveDSD(), which is called from DoSave(), which is called by btnSave_Click and PrepareForPrinting()
4) From frmEntry's saveINV(), which is called from DoSave(), which is called by btnSave_Click and PrepareForPrinting()
5) From frmEntry's btnClear_Click()
</code>```

So the most "interesting" ones are 0, 2, and 3 (I don't think the observed bogus activity takes place in saveINV(), I'm almost positive it's not in the constructor, and I know it's not in btnclearclick()).

So my head is swimming better than Mark Spitz (or, for you young whippersnappers out there, Michael Phelps) ever dreamed of slicing pell-mell through the chlorinated aqua.

Making matters more malevolent for me, I can't step through this code (Windows CE, running in Windows XP mode, no emulator), except in my waterlogged brain*. So I ask: Is there a tool that visually represents all the potential routes from which SetTotalControlsProperties() is called/CurTotal is set? Best of all would be a tool that provided a listing of just what route the code took to get to a designated spot.

Side question: Why is there no "spaghetti" tag? People got arrested for less than this in communist Russia.

Cue (or is it "queue"?) TYA's "Over the Hill" here.

UPDATE

Fresh evidence that there truly is a need for such a tool:

The method that sets the CurTot amount, namely wrkFile.getAmount(), does this:

```<code>public double getAmount()
{
    if (tAmount < 0)
    {
        SetTotalItemsAndTotalAmt();
    }
    return tAmount;
}
</code>```

SetTotalItemsAndTotalAmt() assigns vals based on this query:

```<code>string dynSQL = "SELECT * FROM workTables WHERE name = '" + name + "'";
</code>```

..and "name" here is not passed in to SetTotalItemsAndTotalAmt, nor is it a local var.

Arggghhhhhhhhh!!!

答:
So I ask: Is there a tool that visually represents all the potential routes from which SetTotalControlsProperties() is called/CurTotal is set?

It sounds like you're describing the Call Hierarchy feature found in several IDEs, including Visual Studio:

If you can't use an IDE that has this feature, there are separate tools that generate calls graphs.

Best of all would be a tool that provided a listing of just what route the code took to get to a designated spot.

Any good debugger will display a call stack that you can jump around in, which is exactly what you're asking for here.

SetTotalItemsAndTotalAmt() assigns vals based on this query:

```<code>string dynSQL = "SELECT * FROM workTables WHERE name = '" + name + "'";
</code>```

Umm... Little Bobby Tables alert!!!

Body:
So I ask: Is there a tool that visually represents all the potential routes from which SetTotalControlsProperties() is called/CurTotal is set?

It sounds like you're describing the Call Hierarchy feature found in several IDEs, including Visual Studio:

If you can't use an IDE that has this feature, there are separate tools that generate calls graphs.

Best of all would be a tool that provided a listing of just what route the code took to get to a designated spot.

Any good debugger will display a call stack that you can jump around in, which is exactly what you're asking for here.

SetTotalItemsAndTotalAmt() assigns vals based on this query:

string dynSQL = "SELECT * FROM workTables WHERE name = '" + name + "'";

Umm... Little Bobby Tables alert!!!


问:
How should I unit-test a class that relies on having realistic data?
I have a class that encapsulates the results of a scientific measurement. I’m building in unit tests from the beginning, but I don’t have a lot of experience with unit testing and I’m not sure which behaviors I should be testing and how.

My class does three kinds of things:

Reads measurement data from a file (or a string) into its instance variables

Writes its measurement data out to a file or a string

Performs calculations on its data (e.g. getting the average of a set of numbers)

My approach right now is to include a known-good example data file in my test directory. One test reads the data in from the file, passes it to my class, and makes sure that it meets some basic sanity checks. Another test passes the file’s filename to my class, lets the class read it, and runs the same tests. The remainder of the tests read the data in from the file, pass it to my class, and check that the results of the data-processing methods are correct, given what I know about that data set.

This seems pretty tangled, though. The tests that check (3) implicitly assume that the behaviors of (1) are correct, since it’s the functions in (1) that are being used to populate the class in the first place. And the tests of (1) could benefit from the extensive checks done by the tests for (3). Am I structuring my unit tests poorly, or is this just a natural result of the fact that I need to use a specific dataset in my tests?

答:
What you're doing is integration testing, because as you can probably tell, your tests have dependencies on other parts of your code. This is fine, but it's good to know when you're looking at articles/examples/etc. online.

Some points to consider, and things to remember:

Arrange, Act, Assert. All tests have these 3 steps.

Need more steps? You're probably testing too much for 1 test

No Arrange? You have external dependencies, which almost always makes tests flaky and unreliable.

Lots of Arrange code usually means lots of dependencies, and system-state types of dependencies. That's a recipe for fragile code.

No Act? Often tests the compiler. Leave that to compiler developers.

Lots of Act(s)? You're probably testing too much for 1 test again.

No Assert? Often the case when you want to test that "no errors occurred". No errors != working correctly.

Lots of Asserts? The code under test might be doing too much/touching too many systems. Try refactoring and testing the individual bits instead.

Tests should exist on their own. Avoid scenarios where something that tests 3 depends on the code that does 1. Instead, look to replace the code that does 1 with test code. In your scenario: try manually setting the values to what you want them to be in the test's Arrange step, then perform the Act ion (the calculations), then Assert the result.

Happy-path tests are often a waste of time. Best-case scenarios almost always work. Your tests should be trying to force errors and edge cases.

Do you have a test that passes bad streams to be processed?

Do you have a test that passes null/non-existant filenames to be processed?

What happens if the numeric values to compute are not numeric, or when parsed are huge, or produce huge values when computed?

Surprisingly writing tests rarely confirms that what you've done is right. Instead they give you insight into how usable, stable, and flexible your design is.

edit> This has already been accepted, but I wanted to add something that I learned long ago via Pragmatic Unit Testing:

Unit Testing with your Right BICEP

Are the results Right ?

CORRECT B oundary Conditions

C onform to expected format

O rdered correctly

R ange is correct

R eferences to external dependencies are safe

E xistence (null etc.)

C ardinality

T iming (things happen in the right order, with the correct timing)

I nverse relationships

C ross-Check results with other means

E rrors are forced

P erformance characteristics are within acceptable bounds