问:
Why does the tool offer to change the code - just because it can?
Resharper (or is it Visual Studio - it's a yellow light bulb with a tiny red filament in it) offers to "invert if" on this code:

```<code>if (tItems >= 0)
{
    return tItems;
}
SetTotalItemsAndTotalAmt();
</code>```

...and if I allow it to, it becomes this:

```<code>if (tItems < 0)
{
    SetTotalItemsAndTotalAmt();
}
return tItems;
</code>```

...but then it offers to "invert if" again, and if I gullibly take the bait, it sets it back to its former glory.

If one way is considered better (more grokkable, I guess) than the other, why would it also allow a reverse inversion? And if it's a case of "six of one and half a dozen of the other," why does it even bother to offer a change?

UPDATE

Actually, come to think of it, one of those ways is not even valid, for it says, "WorkFiles.getAmount()': not all code paths return a value" unless it has the return statement outside the if condition.

My guess is this is not Resharper doing this; those Urquell-powered cats wouldn't do such a thing, methinks.

答:
It's ReSharper that's offering this, and it offers it because it can.  There can be many good reasons to let it do so.  I frequently use this when refactoring code like:

```<code>if (cond1) {
   if (cond2) {
      if (cond3) {
         DoSomething();
      } else {
         throw "Error 3";
      }
   } else {
      throw "Error 2";
   }
} else {
   throw "Error 1";
}
return;
</code>```

into:

```<code>if (!cond1) throw "Error 1";
if (!cond2) throw "Error 2";
if (!cond3) throw "Error 3";
DoSomething();
return;
</code>```

It's especially useful when those ifs run on for several screens of code.  And yes, I see code like this often.

Body:
It's ReSharper that's offering this, and it offers it because it can.  There can be many good reasons to let it do so.  I frequently use this when refactoring code like:

if (cond1) {
   if (cond2) {
      if (cond3) {
         DoSomething();
      } else {
         throw "Error 3";
      }
   } else {
      throw "Error 2";
   }
} else {
   throw "Error 1";
}
return;

into:

if (!cond1) throw "Error 1";
if (!cond2) throw "Error 2";
if (!cond3) throw "Error 3";
DoSomething();
return;

It's especially useful when those ifs run on for several screens of code.  And yes, I see code like this often.


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

答:
Unit testing should test two sets of cases:

The very basic cases: is the calculation correct, do the totals add up, etc. Use simple easy to check data for these cases.

The edge cases: delivery date of Feb 29 2016, Order quantity of 999,999, Items with price $0.00, GPS for North Pole (try moving west!) etc. etc.

ContentLicense: CC BY-SA 3.0


问:
Two components offering the same functionality, required by different dependencies
I'm building an application in PHP, using Zend Framework 1 and Doctrine2 as the ORM layer. All is going well. Now, I happened to notice that both ZF1 and Doctrine2 come with, and rely on, their own caching implementation. I've evaluated both, and while each has its own pro's and cons, neither of them stand out as superior to the other for my simple needs. Both libraries also seem to be written against their respective interfaces, not their implementations.

Reasons why I feel this is an issue is that during the bootstrapping of my application, I have to configure two caching drivers - each with its own syntax. A mismatch is easily created this way, and it feels inefficient to set up two connections to the caching backend because of this.

I'm trying to determine what the best way forward is, and would welcome any insights you may be able to offer.

What I've thought up so far are four options:

Do nothing, accept that two classes offering caching functionality are present.

Create a Facade class to stick Zend's interface onto Doctrine's caching implementation.

Option 2, the other way around - create a Facade to map Doctrine's interface on a Zend Framework backend.

Use multiple-interface-inheritance to create one interface to rule them all, and pray that there aren't any overlaps (ie: if both have a "save" method, they'll need to accept params in the same order due to PHP's lack of proper polymorphism).

What option is best, or is there a "None of the above" variant that I'm not aware of?

答:
Do nothing Accept that separate projects can have redundancy as long as they work in their own spaces (not polluting each other caches). Doctrine knows Zend has caching but they don't want to be dependent on Zend and vice versa. Not all people want to use Zend and Doctrine.

I'd let Doctrine code use its own stuff and use ZF for everything else. This way I only need to know ZF classes. Doctrine cache should only be used internally by doctrine for database object. ZF has more front end that's useful outside an ORM, like html page caching front end.

Creating another layer would be ideal but it'll add another dependency to the project, so not very good for maintenance.

I know that in bootstrap it can look redundant to setup multiple caches. It can get worse if you try to use ZF1, Doctrine and ZF2 simultaneously. But it's a very small constant time as they only setup variables, not connecting to the back ends yet.

So, from programming, maintenance and operation perspective, I'd just leave them alone.


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

答:
Depending on platform, this may or may not be possible in a single sql query/without use of a stored procedure.

This problem is effectively equivalent to tree traversal within a table with parent references.  You can construct the tree structure through a self join using a query like this:

```<code>SELECT
    b. *,
    a.event as parent_event,
    a.start as parent_start,
    a.end as parent_end
FROM
    interval_test a
        join
    interval_test b ON b.start >= a.end
order by parent_start, start
</code>```

Producing a result that looks like this:

Note: the result is truncated to save space, but you get the idea...

Each of the possible successors of an event (those with an end >= start of the predecessor) can be thought of as a child in the tree.  You want to find the tree path down the tree that minimizes the start time at each step.

You can do this kind of tree traversal by using recursive queries within SQL Server or using a hierarchical query in Oracle.  This kind of recursion is not supported in MySQL and you will need to use a stored procedure if that is your platform.

For example, in SQL Server, the following query would work:

```<code>        WITH min_path AS
          (SELECT RANK() OVER (ORDER BY a.start ASC) AS [rank], cast(NULL as CHAR(10)) as parent_event,
               NULL as parent_start, NULL as parent_end, a.event, a.start, a.[end]
           FROM dbo.interval_test a
           WHERE a.start=
               (SELECT MIN(START)
                FROM dbo.interval_test)
           UNION ALL SELECT RANK() OVER (ORDER BY c.start ASC) AS [rank], b.event as parent_event,
               b.start as parent_start, b.[end] as parent_end, c.event, c.start, c.[end]
           FROM min_path b
           JOIN dbo.interval_test c ON c.start>= b.[end]
           WHERE [rank]=1)
        SELECT event, start, [end] from min_path where [rank]=1
</code>```

Producing the following result:

Note, there are probably cleaner ways to write the query above for SQL Server.

From a performance perspective, when you are working in an environment with potentially billions of rows as mentioned in the comments above, I don't have a clear idea of how this might perform.  If the query is limited to a small number of events related to a single user it might be fine. Trying to find the whole set of relevant non-overlapping events would probably not work well and you might be better off using a procedural approach.

Title: Logic design question for SQL query

Body:
Depending on platform, this may or may not be possible in a single sql query/without use of a stored procedure.

This problem is effectively equivalent to tree traversal within a table with parent references.  You can construct the tree structure through a self join using a query like this:

SELECT
    b. *,
    a.event as parent_event,
    a.start as parent_start,
    a.end as parent_end
FROM
    interval_test a
        join
    interval_test b ON b.start >= a.end
order by parent_start, start

Producing a result that looks like this:

Note: the result is truncated to save space, but you get the idea...

Each of the possible successors of an event (those with an end >= start of the predecessor) can be thought of as a child in the tree.  You want to find the tree path down the tree that minimizes the start time at each step.

You can do this kind of tree traversal by using recursive queries within SQL Server or using a hierarchical query in Oracle.  This kind of recursion is not supported in MySQL and you will need to use a stored procedure if that is your platform.

For example, in SQL Server, the following query would work:

        WITH min_path AS
          (SELECT RANK() OVER (ORDER BY a.start ASC) AS [rank], cast(NULL as CHAR(10)) as parent_event,
               NULL as parent_start, NULL as parent_end, a.event, a.start, a.[end]
           FROM dbo.interval_test a
           WHERE a.start=
               (SELECT MIN(START)
                FROM dbo.interval_test)
           UNION ALL SELECT RANK() OVER (ORDER BY c.start ASC) AS [rank], b.event as parent_event,
               b.start as parent_start, b.[end] as parent_end, c.event, c.start, c.[end]
           FROM min_path b
           JOIN dbo.interval_test c ON c.start>= b.[end]
           WHERE [rank]=1)
        SELECT event, start, [end] from min_path where [rank]=1

Producing the following result:

Note, there are probably cleaner ways to write the query above for SQL Server.

From a performance perspective, when you are working in an environment with potentially billions of rows as mentioned in the comments above, I don't have a clear idea of how this might perform.  If the query is limited to a small number of events related to a single user it might be fine. Trying to find the whole set of relevant non-overlapping events would probably not work well and you might be better off using a procedural approach.


问:
Are Intel compilers really better than the Microsoft ones?
Years ago, I was surprised when I discovered that Intel sells Visual Studio compatible compilers. I tried it in particular for C/C++ as well as fantastic diagnostic tools. But the code was simply not that computationally intensive to notice the difference. The only impression was: did Intel really do it for me just now, wow, amazing tools with nanoseconds resolution, unbelievable. But the trial ended and the team never seriously considered a purchase.

From your experience, if license cost does not matter, which vendor is the winner?

It is not a broad or vague question or attemt to spark a holy war. This sort of question is about two very visible tools. Nobody likes when tools have any mysteries or surprises. And choices between best and best are always the pain. I also understand the grass is always greener argument. I want to hear all "what ifs" stories.

What if Intel just locally optimizes it for the chip stepping of the month, and not every hardware target will actually work as well as Microsoft compiled? What if AMD hardware is the target and everything will slow down for no reason? Or on the other hand, what if Intel's hardware has so many unnoticable opportunities, that Microsoft compiler writers are too slow to adopt and never implement it in the compiler? What if both are the same exactly, actually a single codebase just wrapped into two different boxes and licensed to both vendors by some third-party shop?

And so on. But someone knows some answers.

答:
It's been said that Intel has released the Intel C++ Compiler v13.0 for Android OS, its first attempt at delivering an optimizing C/C++ compiler designed specifically for Google's mobile platform.

Developers can use the compiler on Linux*-based systems to create apps for Android devices based on Intel processors, including the Intel® Atom™ processor. The Intel compiler is compatible with GNU C++ and developer tools in the Android Native Development Kit (NDK)
You can't use the compiler on just any development machine, either. Neither Windows nor OS X is supported; the tools are only certified for use with Ubuntu 10.04 or 11.04

The current version of the Android NDK uses version 4.6 of the open source Gnu Compiler Collection (GCC) toolchain by default. But Intel's compilers include lots of proprietary optimizations for its own chips, and can often output executable code that performs better than that produced by third-party compilers such as GCC.


问:
Do we need even more web frameworks in C# now that async await is here
Developing endless frameworks for web application, websites and web services is always great fun. It's one of the richest areas where you have 100 different ways of achieving pretty much the same thing.

Even with all this abundance, I've recently managed to find myself missing a web framework in C#.

I feel that the new async-await API of C# 5.0 is really going to change the way server-side code is written. Reaching the zen state of full asynchronicity has always been the holy grail of server-side developers. But it always was too complicated and took too much code. Shamefully, 90% of the web frameworks in the world are still blocking. That's why I think node.js became so popular - it offers cheap asynchronicity.

But now, with async-await, C# is going to steal the show and become the new "asynchronous wonder child". Goodbye JS (in server-side, don't get pissed off). At least that's the case for me, C# just became sexy.

Does this new era call for a new generation of web frameworks?

I'm missing a web framework, or more of a web ecosystem in C# that's reminiscent of node.js Something like node.cs. It's fundamental principals:

Promise of full asynchronicity. Every package in the ecosystem must offer async-await API. I can't even imagine anymore accessing a DB and blocking when doing it. In addition, the core itself should be built around async interfaces - with flows looking like this.

Package-based and modular. C# is notorious for having bloated monolithic web frameworks. I want to mix and match. I want a choice between 10 view engines (written by 10 different people), and a choice between 10 routing engines. These things should not be part of the core.

Lean and concise code. I'm sorry but frameworks in C# never seem agile. Everything is always so overfeatured. Layers and layers of abstractions until you have no idea what's really going on. Don't get me wrong, those huge frameworks are good for many things, just not everything.

Reduce vendor-lock. I'll be nice to offer hosting alternatives to IIS. Maybe come with its own optional async web server like node. Although IIS should be supported as well. Mono support on Linux is important, with async integrations to nginx and friends.

I haven't been able to find an ecosystem with these characteristics. If it existed, it would draw developers towards the great benefits hidden inside the async-await pattern.. that is unique to C# (in production at least).

Edit:

Sorry my question wasn't clear. I'm asking:

Are you familiar with an existing solution that fits my requirements?

If not, do you think it's something worth writing? Do you find it useful? Would you use it as an alternative to the currently available web frameworks in C#?

What critiques and praises do you have for the proposals listed above if I were to create a framework that addresses said proposals.

答:
"Goodbye JS"...  Really?  C# is a server-side language.  The appearance of async in C# is not going to affect client-side languages and frameworks like Javascript at all (except that calls Javascript makes to the server will return faster).

"Does this new era call for a new generation of web frameworks?" The beauty of async is that you can use it anywhere server-side; it doesn't require framework support, nor do you need a special framework to use it.  You can make any C# method asynchronous, just by changing the code and return type a little bit.

You don't need full asynchronicity.  You only need to make asynchronous those long-running methods that are blocking your users.  By that metric, you will find that only about 10% of your methods will need to be made asynchronous.

While the .NET Framework Class Library may seem bloated to you, you don't have to use all of it, or even any of it (well, except for the part that makes ASP.NET and ASP.NET MVC work).  Use only what you need.  Code the rest yourself.

"Layers and layers of abstractions."  Then come up with your own design for your business domain.  Nothing prevents you from doing that.  ASP.NET MVC is already fairly lightweight, and it is both extensible and configurable to your liking.

Vendor lock:  You don't have to use Microsoft's IIS or their compilers; you can use Mono instead.


问:
Should I plan ahead, or figure out programs as I'm writing them?
I was thinking today about Paul Graham's book "Hackers and Painters." More specifically, these two paragraphs:

"I was taught in college that one ought to figure out a program
  completely on paper before even going near a computer. I found that I
  did not program this way. I found that I liked to program sitting in
  front of a computer, not a piece of paper. Worse still, instead of
  patiently writing out a complete program and assuring myself it was
  correct, I tended to just spew out code that was hopelessly broken,
  and gradually beat it into shape. Debugging was a kind of final pass
  where you caught typos and oversights... [It] seemed like programming
  consisted of debugging.

... As far as I can tell, the way they taught me to program in college
  was all wrong. You should figure out programs as you're writing them,
  just as writers and painters and architects do."

That's how it's taught in my college and I'm pretty sure most other colleges as well. You figure out what your program will do, and then you figure out how to do it, then you type and debug. Sometimes you make a basic version and add functionality, but the idea is that you think through and then type.

This sort of reminds of that chapter in Feynman's book called "He Solves Radios By Thinking!" where he paced around thinking of how the radio could be broken, and then fixes it. To me, that's what programming is about - thinking and then finding a solution.

Is this the prevalent approach to coding? If so, why don't more people just hack away and put a program together without having a preconceived idea of what it's going to look like?

What are the advantages and disadvantages of think & type vs. spew & beat?

答:
Generally, programming is an exercise in abstraction. Therefore, any attempt to over actualize any particular solution will undoubtedly lead you to misjudge the scope of your effort.

You are just not that good at judging complexity. Trust me, you just aren't.

The best code starts with an outline of what you want to accomplish and iteratively grown in chunks. With the successive code building upon itself.
In the planning stages of a project it's much more useful to sit down and list what your program is NOT going to do. That way at least you don't succumb to trying to boil the damn ocean.

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


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

答:
The key question here is "is this the most readable, clear and consise way to implement the business logic".

In the case i think the answer is yes.

All the attempts to split up the code only mask the intention without adding anything other than a reduced number of "if"s

This is an ordered list of tests, and a sequence of "if" statements would seem to be the best implementation. Any attempt to do something clever will be harder to read and worse you may not be able to implement a new rule in a "prettier" more abstract implementation.

Business rules can be really messy and there is often no "clean" way to implement them.


问:
call a function and never wait for it in C#
I have a controller in my mvc4 web application in which there is an action that needs to call another function. What happens in that function i.e. the return value is not important for my action. How i can call that function and never wait for it to be executed?

I think it can be done by async but my point is not to use resources, just call the function and never wait for it what ever happens.

Please give me some advise.

答:
```<code>private void Demo()
{
    // Do something, given that the result doesn't matter.
}

public void Do()
{
    Task.Factory.StartNew(this.Demo);

    // The following line will be executed without waiting for the result.
    DoSomethingElse();
}
</code>```

Note that starting a method without caring about the result or about exceptions it can throw is risky.

If an exception is thrown in a Task, it will be hidden until you:

Observe the Result,

Wait() for the task, or:

The GC calls the finalizer on the Task.

You can handle yourself 1. and 2. shortly after you call the method, or you can attach a continuation with myTask.OnComplete(myErrorHandler, TaskContinuationOptions.OnlyOnFaulted) to be run when the original task throws an exception. 3. will crash your process; don't do that.

Body:
private void Demo()
{
    // Do something, given that the result doesn't matter.
}

public void Do()
{
    Task.Factory.StartNew(this.Demo);

    // The following line will be executed without waiting for the result.
    DoSomethingElse();
}

Note that starting a method without caring about the result or about exceptions it can throw is risky.

If an exception is thrown in a Task, it will be hidden until you:

Observe the Result,

Wait() for the task, or:

The GC calls the finalizer on the Task.

You can handle yourself 1. and 2. shortly after you call the method, or you can attach a continuation with myTask.OnComplete(myErrorHandler, TaskContinuationOptions.OnlyOnFaulted) to be run when the original task throws an exception. 3. will crash your process; don't do that.


答:
Obligatory Hunter S. Thomson quote but it always works for me

If you have a clear idea of what you want to achieve, know how to structure your code and are a good coder then its often quicker just to write the code.

Title: Should I plan ahead, or figure out programs as I'm writing them?

Body:
I was thinking today about Paul Graham's book "Hackers and Painters." More specifically, these two paragraphs:

"I was taught in college that one ought to figure out a program
  completely on paper before even going near a computer. I found that I
  did not program this way. I found that I liked to program sitting in
  front of a computer, not a piece of paper. Worse still, instead of
  patiently writing out a complete program and assuring myself it was
  correct, I tended to just spew out code that was hopelessly broken,
  and gradually beat it into shape. Debugging was a kind of final pass
  where you caught typos and oversights... [It] seemed like programming
  consisted of debugging.

... As far as I can tell, the way they taught me to program in college
  was all wrong. You should figure out programs as you're writing them,
  just as writers and painters and architects do."

That's how it's taught in my college and I'm pretty sure most other colleges as well. You figure out what your program will do, and then you figure out how to do it, then you type and debug. Sometimes you make a basic version and add functionality, but the idea is that you think through and then type.

This sort of reminds of that chapter in Feynman's book called "He Solves Radios By Thinking!" where he paced around thinking of how the radio could be broken, and then fixes it. To me, that's what programming is about - thinking and then finding a solution.

Is this the prevalent approach to coding? If so, why don't more people just hack away and put a program together without having a preconceived idea of what it's going to look like?

What are the advantages and disadvantages of think & type vs. spew & beat?


答:
Why don't more people just hack away and put a program together without having a preconceived idea of what it's going to look like?

Many people do just that, throughout their careers.  This site is full of their questions.  The other affiliate sites are full of questions by other people trying to use the software they wrote.

The kind of people who just spew out code, as you put it, will often say something like "Code is its own documentation". Code is not documentation.  Code is not a demonstration of your intent, it's some version of what you remember as the intent, plus a bunch of stuff you got interested in along the way, some of which turned out not to be useful but you didn't have time to remove.  Oh, and that amazing idea you had after two nights of no sleep but much caffeine, which was going to revolutionise the whole project, only know you don't even know how it compiles, let alone what it was supposed to do - or precisely what effect it will have if you remove it.

Without some kind of design document, however minimal, how do your collaborators (or successors) tell which bits to extend and which to drop?  That document doesn't have to be written at the beginning, but for a project of any size and worth it needs to happen at some point.

Spew-and-refactor works for solo projects, up to a point (and people who are good judges of where that point is are worth knowing).  It's less practical for teams; how do people work efficiently in parallel without some minimal consensus about the spec?  Agile methodology is largely an attempt to resolve that problem without killing people's native enthusiasm for coding.


问:
How to combine search words? AND or OR?
I have a basic search in my webpage. When I designed it, I chose to combine the search box inputs with OR. For example: A search for foo bar will be translated to foo OR bar, so every entry which includes foo or bar will be shown.

I did this because I thought that a search should return as much as possible and leave it to the user to search with AND (a search for foo and bar will return only the entries that contain both).

When the customer tested it, he tried a lot to search for 'foo bar' and wasn't able to find the right entry because the search returned to much. It seems confusing to him that a search for foo bar could return entries where one of the search inputs is included and not both.

What is the best way to combine search words (when the user doesn't provide any combining info)? Should I use foo AND bar or foo OR bar?

答:
This is a usability question (for UX.SE). Ideally, you would

first produce the most relevant results (the ones with the exact phrase entered),

then the results with search keywords (and their inflections) adjacent to each other,

then the results for the AND operation on search by individual keywords/their inflections (i.e. anywhere in the document),

and lastly, results with OR (sorted in descending order by any kind of relevance score on a search by individual keywords, their inflections and, possibly, synonyms).

I wouldn't go too far though: catching mistyped search terms may be added much later as I'm not entirely convinced of its utility. Parsing for extended Boolean logic formulas

```<code>LIKE "keyword*" AND ("text" ADJ "inflection")
</code>```

is for advanced users.

You can also separate the parts visually.

Note: update based on Marjan Venema's helpful comment.

Title: How to combine search words? AND or OR?

Body:
This is a usability question (for UX.SE). Ideally, you would

first produce the most relevant results (the ones with the exact phrase entered),

then the results with search keywords (and their inflections) adjacent to each other,

then the results for the AND operation on search by individual keywords/their inflections (i.e. anywhere in the document),

and lastly, results with OR (sorted in descending order by any kind of relevance score on a search by individual keywords, their inflections and, possibly, synonyms).

I wouldn't go too far though: catching mistyped search terms may be added much later as I'm not entirely convinced of its utility. Parsing for extended Boolean logic formulas

LIKE "keyword*" AND ("text" ADJ "inflection")

is for advanced users.

You can also separate the parts visually.

Note: update based on Marjan Venema's helpful comment.


答:
This totally depends on the use case of course there may be many applications where OR would be the right thing to do.

In general I think most users (especially if not very experienced) will understand the AND variant better. That way (as your customer says) you can reduce the amount of results very easily.

But there are cases for OR too of course. Especially when there may be information in the text search where several variations to write something may exist and the user can't know which one was chosen.

As a conclusion: I would start with the AND as the basic assumption (unless there is a strong indication that this is wrong for your specific kind of data). But I would also try to provide some simple syntax that would allow the experienced user to fallback to use OR (and maybe more options). Maybe a search string like this: test [maybe1 OR maybe2 OR maybe3] which would look for a text that contains 'test' and at least one of the other options.

Depending on your search engine you can get around this problem somehow if you can sort by relevance. In this case for some use cases the amount of results may be less relevant because those with most keyword hits would be sorted on top.

Title: How to combine search words? AND or OR?

Body:
I have a basic search in my webpage. When I designed it, I chose to combine the search box inputs with OR. For example: A search for foo bar will be translated to foo OR bar, so every entry which includes foo or bar will be shown.

I did this because I thought that a search should return as much as possible and leave it to the user to search with AND (a search for foo and bar will return only the entries that contain both).

When the customer tested it, he tried a lot to search for 'foo bar' and wasn't able to find the right entry because the search returned to much. It seems confusing to him that a search for foo bar could return entries where one of the search inputs is included and not both.

What is the best way to combine search words (when the user doesn't provide any combining info)? Should I use foo AND bar or foo OR bar?


问:
Algorithm to arrange objects so that the total length of edges between them is minimized?
We are given a list of edges between a set of N vertices. There are atmost three edges joining a vertex. We have to arrange all the vertices on a straight line with the positions numbered from 1 to N so that the sum of the length of all the edges is minimized.

The length of an edge a,b is the difference between the positions of vertices 'a' and 'b' on the line. There are atmost 12 vertices.
The algorithm should work within the time limit of 1 second.

This is the actual problem.

I have tried solving this problem by trying all the permutations and finding out the total cost of each edge. But this work only for 8 out of the 12 test-cases to the problem. Because in the worst case the total number of operations is proportional to 12! * 18.

The size of N is very small so I think the solution might be similar to trying all the possibilities.

I don't need the complete solution to this problem because I want to try to come up with it myself but only a hint on how can I optimize my algorithm so that it works within the time limit.
Thanks.

答:
I would try to attack this problem similar to the eight-queens puzzle

generate permutations incrementally

for each placing of the elements 1,..,k, k<N, you can easily calculate a lower bound for the final score without generating all of the final placings of k+1,...,n. For example, you could ignore the fact that k+1,...,n have to be placed on different spots and calculate their scores assuming each of that vertices could be placed at the "optimal  spot"

completed permutations give you an upper bound for the final score; this upper bound will decrease the more permutations you generate

whenever the lower bound for a partial placing exceeds the upper bound, you can cut the search tree here and stop further placings of k+1,...,n

This technique is also called branch-and-bound.

EDIT: there are of course further optimizations possible. For example: when looking for a place for vertice k, don't try the empty slots from left to right, but pre-sort the empty slots, so that the places with lowest score increasement will be tried first. This will most probably bring the upper-bound quickly, which improves the chance to cut the search tree.

EDIT2: permutation generation defines a search tree. One node consists of k elements already placed in a slot, and the siblings of this node are the (n-k) nodes where one more element is placed in a free slot. You can assign each node a lower-bound score, as I wrote above. But instead of making a depth-first search through this tree, you put the nodes into a priority queue. The algo then takes the node with minimum score first out of the prio-queue, generates the siblings, calculates the lower bound score for each sibling and inserts those nodes into the prio-queue again. When you reach a node where all vertices are placed in a slot, you have found the optimal solution. This is called A* search. It is easy to implement when you have a ready made priority queue at hand.


答:
I know this doesn't give you the solution, but have you considered looking into the subject of information retrieval? I've done this at university, and based on what I can remember, it works in the following way:

You have documents

You have a search term

You can then use probability to scan your document using the search terms

You would then end up with vectors representing your results. There will also be a vector for your search term. The angle between the vectors will show close your term is in relation to the document. Smallest angle between vectors will represent best match, when biggest angle will represent worst match.

Title: How to combine search words? AND or OR?


问:
Which if statement requires less computation?
I have

```<code>if (!b && c || a && c)
  //do action a
else
  //...
</code>```

Due to some internal relationship between a, b, and c. !b && c || a && c is proved to be equivalent to (! a && b) || c.

I just wonder will (! a && b) || c be simpler than !b && c || a && c? Can you prove it? Assume the chances of a,b,c to be True or False is equal.

I'm not asking which style is better. I'm asking which statement has lower computational complexity. Just like asking quick sort and Bubble Sort, which has lower computational complexity. You will not answer it depends, it is related to compiler and hardware because some hardware have special instruction for Bubble Sort. I hope to hear nlog(n) and n^2.

答:
Are you sure it's

```<code>(! a && b)
</code>```

rather than

```<code>!(a && b)
</code>```

?

If not, the brackets are unnecessary and just lead to confusion.

Either way, generally the less operations you have the better for the computer, and in both AND or OR conditions it's better to put the "simplest" first, your most effective way of writing this for the computer (not necessarily the reader) would be:

```<code>c || b && ! a
</code>```

This is assuming C-style operator precedence for the logical operators.

Body:
Are you sure it's

(! a && b)

rather than

!(a && b)

?

If not, the brackets are unnecessary and just lead to confusion.

Either way, generally the less operations you have the better for the computer, and in both AND or OR conditions it's better to put the "simplest" first, your most effective way of writing this for the computer (not necessarily the reader) would be:

c || b && ! a

This is assuming C-style operator precedence for the logical operators.


问:
What do I call people who extend my class in base class documentation?
Been calling them "implementers", but it seems weird to me.

```<code>/// <summary>
/// Implementers should implement this.  Derp
/// </summary>
protected abstract void InternalExecute();
</code>```

A point of clarification, I'm interested in what to call the people who create child classes, not the child classes themselves.

"Hey, you there" not "that thing there."

答:
Users

IE, users of the base class.

ContentLicense: CC BY-SA 2.5

Body:
Users

IE, users of the base class.


答:
a good optimizer will make any difference here moot

you can think in how the short circuit works:

with if ((!b && c) || (a && c)) you get

```<code>if(b)goto OR2;
if(c)goto then_lbl;
OR2:
if(!a)goto else_lbl;
if(!c)goto else_lbl;
then_lbl://...
</code>```

while with if((! a && b) || c) (the actual equivalent) you get

```<code>if(a) goto OR2;
if(b) goto then_lbl;
OR2:
if(!c) goto else_lbl;
then_lbl://..
</code>```

so there is no real difference (you always go through 2 or 3 branches)

But I'll repeat my point: this kind of micro optimization is utterly useless to worry about unless it is part of a provable bottleneck and most times the problem isn't a malformed if statement

here you'll find that readability trumps speed

Title: Which if statement requires less computation?

Body:
I have

```<code>if (!b && c || a && c)
  //do action a
else
  //...
</code>```

Due to some internal relationship between a, b, and c. !b && c || a && c is proved to be equivalent to (! a && b) || c.

I just wonder will (! a && b) || c be simpler than !b && c || a && c? Can you prove it? Assume the chances of a,b,c to be True or False is equal.

I'm not asking which style is better. I'm asking which statement has lower computational complexity. Just like asking quick sort and Bubble Sort, which has lower computational complexity. You will not answer it depends, it is related to compiler and hardware because some hardware have special instruction for Bubble Sort. I hope to hear nlog(n) and n^2.

Body:
a good optimizer will make any difference here moot

you can think in how the short circuit works:

with if ((!b && c) || (a && c)) you get

if(b)goto OR2;
if(c)goto then_lbl;
OR2:
if(!a)goto else_lbl;
if(!c)goto else_lbl;
then_lbl://...

while with if((! a && b) || c) (the actual equivalent) you get

if(a) goto OR2;
if(b) goto then_lbl;
OR2:
if(!c) goto else_lbl;
then_lbl://..

so there is no real difference (you always go through 2 or 3 branches)

But I'll repeat my point: this kind of micro optimization is utterly useless to worry about unless it is part of a provable bottleneck and most times the problem isn't a malformed if statement

here you'll find that readability trumps speed


问:
In MVC is it considered good practice to have private, non-action, functions in a controller class?
Sometimes action functions in the controller class can become huge and nasty, with many-many lines of code to simply control the flow of data from the Model to the View. At some point these huge functions completely lose track of the basic principles of good code, i.e. only doing one thing, being small, readable and manageable etc.

Would it be considered good practice to break these huge action functions into smaller private functions in the controller class or should the need of such optimization mean we should rather add them in the model?

I would vote for having the smaller functions as private in the controller so that they are relative to the action, but I have heard arguments that the controller should preferably be simple while the model can get huge and clumpy; and was just wondering which one would be the most preferred method.

答:
The best answer I can give is to quote from the great book by Robert Martin, "Clean Code" that I highly recommend to anyone interested in the subject:

The first rule of functions is that they should be small. The second rule is that they should be smaller than that.

Can't say it better. Another great quote from the same book applies:

Functions should do one thing. They should do it well. They should do it only.

When splitting your code into more functions, you are forced to give those functions meaningful names that can greatly improve readability of your code.
Needless to say, all functions not intended for use outside the class, should be private, so you can easily re-use your code via inheritance.

If your controller now has too many functions, it is a sign that it probably does too much. Then you may split it into several independent pieces or try to move some functions to models as mentioned in the other answer. Also if you follow non-classical MVC flavour, where Views are allowed to have some logic, you can put some of your functions there whenever it fits.


问:
Can you call any php model class in an MVC from the controller?
I'm creating a simple MVC at the moment and am wondering if it's 'correct' to be able to call any model class directly from the controller to get the data to send to the view?

I have the following folder structure:

```<code>.htaccess
index.php
/controller
/model
/templates
</code>```

I also have the needed model classes within the /model folder, at the moment I've tried playing with a /model/model.class.php to try and build all parts of the site but it's already starting to become huge and I think it might be better to completely cut it out.

I'm thinking the better approach is to use:

```<code>elseif($_GET['type'] == "Profile") {
    $profile = new thread($userId);
    $comments =  $profile->getComments();
    require "templates/profile.php";
}
</code>```

The above is a brief example but is that how a controller could/should/might look or was the first approach better or am I completely missing the point of the model and controller communication?

答:
The problem with this traditional folder structure is that you have to place e.g. models and views that belong together into different folders. That may create a nightmare. I personally find it hard and time consuming to navigate huge directory structures.

Instead, I found it helpful to follow advice from Derick Bailey's Blog and put all components that belong to one module into corresponding folder. That way you also avoid huge directories but rather have more directories with meaningful names.

Now in your question the word "any" is confusing. If you mean to be able to call any single functions, then certainly no - only those you really need. Otherwise - yes:) (see any source on MVC).


问:
Model-View-Controller: who caches the data?
I am building a GUI to interface an embedded device to a PC host. The GUI provides control over the device parameters and displays some feedback from it. The GUI also has to emulate some of the device functionality and present it to the user.

I have been advised to use a Model-View-Controller pattern, so that if the device does not acknowledge some command, the the user knows about the ineffectiveness of his actions.

Trouble is, I cannot decide which component(s) should cache data. Example: when a value is printed on the screen, the view clearly has to know it. However, the model also has to know it, as it uses it to calculate other values. Furthermore, the controller also has to know it as, for example, the value change could be proportional to a logarithm of the user action.

How do I pull this off properly?

答: I would use additional Model (or Collection of those, which is again a Model) for cacheing. Then use event drivent architecture, where my View emits Events representing user interactions, to which my Caching Model would listen. The Model can emit events and so on. That way all components are nicely isolated and only communicate via events. And if Controller needs to do anything, again make it listen to events.</p>


问:
Access JSON object in different Languages
I have a Java code which is writing some data in string format to Messaging queue. Now any one can subscribe to this queue and fetch this data. Here the client fetching this data can be written in any programming language.

I was planning to expose this data in JSON format, but then as per my understanding I have to expose my Bean Object, as the Object is needed to parse this JSON string. And in this case I am limiting client to be Java only.

I don't want to have any of such a limitations, so now I am looking to expose this data as XML.

Any other way so that I can still use JSON here?

答:
You can't do something that contains anything and is readable for everyone. That is why you need data transfer objects on both sides. You can deserialize JSON sent by Java in C# for instance, but C# client has to know what he is trying to deserialize.

Of course it is not really strict so you can send some fields of object in JSON and deserialization will set not present fields to default values.

Some languages have possibility to use anonymous objects so it would be possible, but later on you will have to know what you want to do with it.

Long story short, either way client has to know what he gets, but you can write documentation about sent fields, serialized to JSON Java class documentation would be enough for other developer to receive stuff and translate it to his language.


答: http://www.json.org/ shows a list of JSON libs and resources for more than 50 programming languages. You have to decide if that is enough support for your case. Nevertheless, there are indeed situations where XML (still) is better suited. For example, MS Excel has native XML support, but no native JSON support (though one can come around this restriction, see here, for example).</p>

Title: Access JSON object in different Languages

Body:
I have a Java code which is writing some data in string format to Messaging queue. Now any one can subscribe to this queue and fetch this data. Here the client fetching this data can be written in any programming language.

I was planning to expose this data in JSON format, but then as per my understanding I have to expose my Bean Object, as the Object is needed to parse this JSON string. And in this case I am limiting client to be Java only.

I don't want to have any of such a limitations, so now I am looking to expose this data as XML.

Any other way so that I can still use JSON here?


问:
Is there a name for the concept of a "cumulative checksum"?
Insofar as I understand it, tools like Git and Mercurial derive checksums from their data, and those checksums are used to derive other checksums used in aggregate, leading to a kind of accumulative checksumming (checksums being the input to other checksums), that ensures a high level of integrity.

Is there a name for that, and if so, what is it? (Other than "accumulative checksumming" (which, according to Google, is not well used, or I just made up.) My Google foo is failing me here...

Another way to put it, is there a name for the way a Git repository ensures its integrity?

Sorry for the vagueness - grasping for terminology I sense should exist but I can't actually find.

答: You understand it correctly. A Git initial commit checksum can be used to identify the entire repo. I have never heard / seen an exact term for it. It's just a method of ensuring integrity, as you said.</p>


答:
As far as I'm concerned it's still just "checksum".

The "sum" part of the name is a little misleading - the algorithms used to create checksums usually involve much more than just addition*. When you aggregate checksums, you're really just creating a more complicated algorithm.

* In fact, checksum algorithms which just involve summing are typically going to do a much poorer job of detecting differences.

Title: Is there a name for the concept of a "cumulative checksum"?

Body:
Insofar as I understand it, tools like Git and Mercurial derive checksums from their data, and those checksums are used to derive other checksums used in aggregate, leading to a kind of accumulative checksumming (checksums being the input to other checksums), that ensures a high level of integrity.

Is there a name for that, and if so, what is it? (Other than "accumulative checksumming" (which, according to Google, is not well used, or I just made up.) My Google foo is failing me here...

Another way to put it, is there a name for the way a Git repository ensures its integrity?

Sorry for the vagueness - grasping for terminology I sense should exist but I can't actually find.


答:
It's called a hierarchical checksum.

The corresponding tree is known as a Merkle Tree or hash tree or more rarely authentication tree.


答:
I would call it a recurrence checksum.

In mathematics, a recurrence relation is used for a sequence recursively defined, starting with an initial value, and where the following term is defined from the previous one: u(0)=u0, u(n+1)=f(u(n)).

The git checksum mechanism is a typical example of that kind of function. I would stick with the commonly-accepted term in the mathematical circle, which is usually intersecting with the computer science one.

For another version of a recurrence checksum, please see this paper on rolling checksum, used by rsync. However you can't generally call them rolling checksum as this algorithm is only a special case.


问:
LIcense Issues Of Publishing A WordPress Theme, Built With Roots Theme, At Themeforest
I want to develop a WordPress theme using Roots theme framework and then sell it on themeforest.net.

Roots theme license allows me to sell the theme as per its founder's discussion with some guy on this google group post.

It says that the product should have an MIT compatible license. The question is:-

If I sell it on themeforest then will it be under compliance with the MIT license? I believe that themeforest has its own 'regular license'.

Will the purchaser of the theme have the right to modify my theme's source code and sell it again on themeforest?

Note: I don't have much knowledge of the licenses, that's why I'm here. Please don't ask me to read the license because I'm unable to understand their complex English. "INCLUDING BUT NOT LIMITED", "AS IS", "TORT OR OTHERWISE" etc. Can't understand it clearly.

答:
Here is a summary of some popular licenses I keep handy.

MIT: Do basically whatever you want. Just don't claim you wrote it, and don't try to sue anybody.

GPL: You can do whatever you want with the code as long as your code is GPL too. You can't use it closed-source projects. You can't restrict the next person in any way.

LGPL: GPL except some restricted forms of closed-source use are OK. I believe the idea is that you can use an LGPL library in a closed-source project. Really, both the GPL and LGPL are way too confusing.

BSD: Essentially equivalent to MIT.

Microsoft Public License: Essentially equivalent to MIT.

Apache License: Essentially MIT, but you have to make sure people know that you modified the code (if in fact you did).

Selling on Themeforest will be under compliance with MIT, and the purchaser can change your source but must attribute you for the original codebase. As to whether they can resell it, I am also unsure, I assume they can.


问:
Cogent arguments for 'semantic css' over 'object oriented css'
[Context - I'm a Java developer, having a discussion with a designer who works in the html/css space]

I was having a discussion with a co-worker today about the merits of 'semantic css'.

His response was, "Oh we're not interested in semantic css, we use object oriented css"

I understand what he means, ie that they're using the 'inheritance' properties of css and SASS mixins to describe styles. But I feel like he has not tried to understand 'semantic css'.

I'm trying to construct a cogent argument about why 'object oriented css over semantic css' is flawed.

This is my reasoning so far:

“css isn’t object oriented” https://stackoverflow.com/a/7431746/15441

Write html code with semantic components http://css.dzone.com/articles/object-oriented-css-crap-long

Examples of layout out your page with semantic components http://woork.blogspot.com.au/2008/11/css-coding-semantic-approach-in-naming.html

Examples of non-semantic naming http://css-tricks.com/semantic-class-names/

My question is "what are some cogent arguments explain semantic css to someone who thinks that 'inheritance', 'classes' and 'mixins' make something object oriented and that he doesn't need to worry about good naming?"

答:
Thanks for your comments - I've been able to clarify my thoughts on this.

The distinction between the two seems to be on workflow. The former (object oriented css) is more of a traditional print based approach where colours and styles are chosen first for a branding goal, and then the website is assembled from that later. The latter (semantic css) approach is more clearly linked to a website design goal, where a site can be built and the styles can be easily tweaked later, without necessarily changing the code on the page.

If you have a workflow that goes graphic designer does colours and style -> css designer -> web developer, and the styles are unlikely to change - then an object oriented css approach is more appropriate (but less flexible later).

If you have a workflow where the graphic designer and css person will work iteratively to tweak the website to a particular goal - then semantic css is more appropriate.

The big distinguishing criterion is that semantic css allows customisation to the site by changing the style without the site.

(There is probably an outstanding question about whether the design goal of css intended you to be able to tweak the site without changing the code of the page - but that's a discussion for another day)

(I do appreciate the comments that say that good naming is the main thing you're worried about. My point is that you should name the page elements first and then build styles from that - rather than build css elements and then pick and choose them into your page)


问:
What arguments can I use to justify the use of either XML or JSON to store and transmit object data?
My project lead considers both of these approaches to be unnecessary overhead. I have been involved in and have witnessed a lot of talk around XML vs JSON, but this is the first time that I have heard an argument against BOTH.

We are using c# in .Net 4. We'll be storing data in a sql server database on the server and also on mobile devices. I've heard all the arguments between the two but now I need to understand the arguments for and against the use of any object notation to store data - my project lead prefers csv format.

答:
It's all about the trade off between the size of transmitted data (and hence the time taken to transmit it) and the ease of converting it to / from your class objects.

A hand crafted binary format will have a smaller size then JSON or XML, but will that require much more effort to code and test routines for serialisation / de-serialisation.

Just about every programming language / platform has mature and well tested libraries for XML and JSON that you can plug in with minimal effort.


问:
How would I design an interface such that it's clear which properties may change their value, and which will remain constant?
I am having a design issue regarding .NET properties.

```<code>interface IX
{
    Guid Id { get; }
    bool IsInvalidated { get; }
    void Invalidate();
}
</code>```

Problem:

This interface has two read-only properties, Id and IsInvalidated. The fact that they are read-only, however, is by itself no guarantee that their values will remain constant.

Let's say that it were my intention to make it very clear that…

Id represents a constant value (which may therefore be safely cached), while

IsInvalidated might change its value during the lifetime of an IX object (and so shouldn't be cached).

How could I modify interface IX to make that contract sufficiently explicit?

My own three attempts at a solution:

The interface is already well-designed. The presence of a method called Invalidate() allows a programmer to infer that the value of the similarly-named property IsInvalidated might be affected by it.

This argument holds only in cases where the method and property are similarly named.

Augment this interface with an event IsInvalidatedChanged:

```<code>bool IsInvalidated { get; }
event EventHandler IsInvalidatedChanged;
</code>```

The presence of a …Changed event for IsInvalidated states that this property may change its value, and the absence of a similar event for Id is a promise that that property will not change its value.

I like this solution, but it's a lot of additional stuff that may not get used at all.

Replace the property IsInvalidated with a method IsInvalidated():

```<code>bool IsInvalidated();
</code>```

This might be too subtle a change. It's supposed to be a hint that a value is computed freshly each time — which wouldn't be necessary if it was a constant. The MSDN topic "Choosing Between Properties and Methods" has this to say about it:

Do use a method, rather than a property, in the following situations. […] The operation returns a different result each time it is called, even if the parameters do not change.

What kind of answers do I expect?

I am most interested in entirely different solutions to the problem, along with an explanation how they beat my above attempts.

If my attempts are logically flawed or have significant disadvantages not yet mentioned, such that only one solution (or none) remains, I would like to hear about where I went wrong.

If the flaws are minor, and more than one solution remains after taking it into consideration, please comment.

At the very least, I would like some feedback on which is your preferred solution, and for what reason(s).

答:
I would prefer solution 3 over 1 and 2.

My problem with solution 1 is: what happens if there is no Invalidate method? Assume an interface with an IsValid property that returns DateTime.Now > MyExpirationDate; you might not need an explicit SetInvalid method here. What if a method affects multiple properties? Assume a connection type with IsOpen and IsConnected properties – both are affected by the Close method.

Solution 2: If the only point of the event is to inform developers that a similarly named property may return different values on each call, then I would strongly advice against it. You should keep your interfaces short and clear; moreover, not all implementation might be able to fire that event for you. I'll re-use my IsValid example from above: you would have to implement a Timer and fire an event when you reach MyExpirationDate. After all, if that event is part of your public interface, then users of the interface will expect that event to work.

That being said about these solutions: they aren't bad. The presence of either a method or an event WILL indicate that a similarly named property may return different values on each call. All I'm saying is that they alone are not enough to always convey that meaning.

Solution 3 is what I'd be going for. As aviv mentioned, this may only work for C# developers though. To me as a C#-dev, the fact that IsInvalidated is not a property immediately conveys the meaning of "that's not just a simple accessor, something is going on here". This does not apply to everyone though, and as MainMa pointed out, the .NET framework itself is not consistent here.

If you wanted to use solution 3, I would recommend to declare it a convention and have the whole team follow it. Documentation is essential too, I believe. In my opinion it's actually pretty simple to hint at changing values: "returns true if the value is still valid", "indicates whether the connection has already been opened" vs. "returns true if this object is valid". It wouldn't hurt at all though to be more explicit in the documentation.

So my advice would be:

Declare solution 3 a convention and consistenly follow it. Make it clear in the documentation of properties whether or not a property has changing values. Developers working with simple properties will correctly assume them to be non-changing (i.e. only change when object state is modified). Developers encountering a method that sounds like it could be a property (Count(), Length(), IsOpen()) know that someting's going on and (hopefully) read the method docs to understand what exactly the method does and how it behaves.


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

答:
Its actually a pretty easy situation to get into when you're coding for yourself.  Its bad to spend a long time focusing on the best way to do something when you don't produce anything in the end.

However I think it's also bad to never stop and reflect. You are pretty much a beginner with only a few months dev. experience if I read your question right.  At this point in time you should be focusing on writing something, anything. If you're writing for yourself. If you're not writing for yourself you'll learn to be quicker as if you don't your job will be in trouble.

My advice is

Write code. Bad code / good code it doesn't matter at this stage. You just need to know you can bash something out when required.

Set yourself deadlines. Try to be reasonable with them but not so loose as you may as well not have any deadlines.

Don't try to alter functioning code to be better written unless.

You have a performance issue you need to fix.

You have enough time and you feel that your new way is an awful lot better.

You feel you can learn something new by trying to implement in a different way.

Pay attention to the small details, such as comments. It can really help you fix your mind on the problems and the solutions with your own code when you comment it.  Try it, it allows you to step away from the solution and focus on the problem.

Get other people to review your work if possible.

If doing this as a hobby enjoy it. If the worrying about the problems is taking away from your enjoyment, it implies your doing something wrong.

Ask people what they would do with the same problems. This may be the best site for that.

Code that functions but is written badly is a lot more useful than no code.

One last comment that may help you. The interface to your code is a lot more important than the code itself.

Finally In time you will gain speed and confidence. If you can't look back at your work in a years time and say "What was I thinking?" then you really haven't learn't enough.

OwnerDisplayName: Mash


答:
The benefits of binary: smaller size, and faster (de)serialisation. The small size can also mean faster transmission, especially if you're using a slow network (eg mobile).

Sure, the programmer might have more work to do but that depends on the library used to perform the  serialisation. If you're using a JSON or XML library to do this, I would expect that you could replace the internals of that library with a binary protocol and not even notice the change. (in fact, I know this - we did it once, our serialisation lib was XML, when we replaced the object with a binary version, overall performance of our program increased by 20%).

I would expect that the only true benefit of JSON or XML is that a human can read the data whilst it is serialised. Whether this really is useful depends if you're using the data for storage or just for communication. Even then, create a tool to show you the contents.

Incidentally, csv format is still just as bad - the split is fundamentally between some form of textual format, or a binary one. Given the choice between csv, xml or json ... I would have to say "what's the data stored", csv can be a very good choice for a lot of data, especially as you already have a tool to manipulate it (a spreadsheet) or to import it into a database. If the data is hierarchical in some way (eg a graph or tree) then csv isn't such a good choice.

Title: What arguments can I use to justify the use of either XML or JSON to store and transmit object data?

Body:
My project lead considers both of these approaches to be unnecessary overhead. I have been involved in and have witnessed a lot of talk around XML vs JSON, but this is the first time that I have heard an argument against BOTH.

We are using c# in .Net 4. We'll be storing data in a sql server database on the server and also on mobile devices. I've heard all the arguments between the two but now I need to understand the arguments for and against the use of any object notation to store data - my project lead prefers csv format.


问:
Formal name for left/right-hand-side of an expression
Given an expression, such as int x = y + 5, we'd call int x the left-hand side (or LHS), and y + 5 the right-hand side (or RHS). The whole expression is called, of course, an expression (or equation), but is there a generic term for a "side" of an expression?

LHS and RHS don't quite cut it when it comes to an expression such as int x = y = 5 (gloss over the fact here that such assignments are generally bad practice!).

I'm toying with the term component to describe any "side", but was interested to see if there was a formal standard term already in use. Wikipedia only has "Sides of an equation", any better suggestions?

答:
I think you're looking for the word operand. A unary operator has one operand. A binary operator has two operands; if the operator is infix, i.e. if the expression is written horizontally with the operator between the two operands, then the operands are known as the left-hand side and right-hand side (very commonly abbreviated LHS and RHS). There are other names when the operator is written differently, for example numerator and denominator for the fraction operator arranged vertically and marked by a horizontal bar. A ternary operator has three operands (which don't have standard names; if they're written from left to right, you might call them left, middle and right operand), and so on.

Assuming C, x ? y : z has three operands for the ?: operator which are x, y and z. The syntactic element int x = y = 5 is not parsed as an expression with a single operator; x, y and z are subexpressions but so is y = 5. y and 5 are operands of the operator =. There is no generic term to designate x and y = 5 here: in general parsing terminology, they are operands of the declaration operator, but in C terminology, the word operand is reserved for things that C calls operators.

If you want to treat int _ = _ = _ as a single unit (which isn't how C syntax works), you can refer to the pieces as the left, middle and right subterms.

The word subterm can be used more or less interchangeably with subexpression in general parsing literature, but specific languages often make a difference between the two (often an expression is a particular kind of term, but occasionally it's the opposite). You can refer to subterms which are one step down from a node in the parse tree as immediate subterms.

A term that cannot be decomposed any further is an atom.


答:
The two statements have the same computational complexity. Both execute in constant time (in complexity terms), which can be written O(1). Since the number of input states is finite (8), it could hardly be otherwise.

If a, b and c are general expressions rather than variable, !b && c || a && c may cause c to be evaluated twice. If c is not idempotent (i.e. if running c a second time doesn't necessarily do what it did the first time), all bets are off. The two expressions you propose also don't execute a, b and c in the same order in all cases, so if their running time depends on the order in which they are called, again, all bets are off.

If what you're wondering is not, in fact, the computational complexity (which deals with asymptotic measures of amounts of computation) but exact the number of computation steps, then the answer is that there is no general answer. The exact number of computation steps depends on which model of computation you choose. For asymptotic analysis, the choice of model is mostly irrelevant: any reasonable model gives the same result (or sometimes there are a few reasonable choices of model, and you need to say which one you're using). If you want a finer analysis, you have to provide a detailed model.

It is completely useless to refine the analysis in this case because the practical difference is going to hinge on a lot of factors that cannot readily be predicted, including:

what machine code the compiler generates (which depends on the compiler, the compiler version, the optimization settings, the target CPU, and the surrounding code);

the exact model of CPU (since this will be affected by the amount of prefetching, the branch prediction, the instruction and data pipelines depth, etc.);

what other code executed before (since this influences the state of the pipelines, the cache, the branch predictor, etc.).


问:
Does macros support make Scala a Lisp dialect?
I've read recently that macro support in Scala is now official. I checked the documentation page and they are reminiscent to the LISP ones. In one of his essays Paul Graham writes that when "you add this final increment of power" to a language it is no longer a new one but a lisp dialect.

Is this the case with Scala? It does not seem like a LISP dialect to me and the macro support in Scala is somewhat awkward for me.

答:
Not in any way that one would normally identify a Lisp. I believe Paul Graham is hyperbolizing here a bit. He's an extremely big proponent of Lisp-family languages (having written one himself).

As far as I know, these are some of the general traits all Lisps share:

Homoiconicity (Code is data, data is code - this is visually obvious from the structure of a Lisp program)

Dynamic Typing (Possibly with optional type annotations)

Polish Notation for all function calls (Prefix only, not infix operators)

You might be able to remove one element or so from those and still argue that your language is close enough to the Lisp family to be considered a Lisp. Scala, on the other hand:

Is not homoiconic (With a syntax more similar to Java)

Is heavily statically typed

Supports prefix, infix and postfix "operators" (functions)

Unless you define a Lisp simply to be "A language with Macros", Scala doesn't fit the bill.


答:
The Lisp family of languages is a fuzzy concept. The key aspects seems to be

Support for functional programming

Macros

Homoiconic (The text <=> The AST, eg Lisp's love of parens)

Dynamically typed

Garbage Collected

The big place where Scala falls down in is 3. Scala is hilariously not homoiconic and this is not a bad thing necessarily.

It does have one major effect though: in Lisps, part of what makes macros so powerful is that they're so easy. In common lisp a macro is literally a function that returns a list. That's it.

In Scala or Haskell (Template Haskell), compile time meta programming is something that experts do, in Lisp, macros are what everyone does.

Scala also fails 4 being very strongly statically typed. There are pragmatic ways that you can convince the compiler to accept some level of dynamic typing, but you're definitely fighting the language then.

My thought is that Scala, like many, is influenced by Lisp, but it isn't a dialect.

Title: Does macros support make Scala a Lisp dialect?

Body:
I've read recently that macro support in Scala is now official. I checked the documentation page and they are reminiscent to the LISP ones. In one of his essays Paul Graham writes that when "you add this final increment of power" to a language it is no longer a new one but a lisp dialect.

Is this the case with Scala? It does not seem like a LISP dialect to me and the macro support in Scala is somewhat awkward for me.


答:
No, Scala is obviously not a Lisp dialect in any meaningful sense. If you look at what he says:

I mention this mostly as a joke, but it is quite true. If you define a language that has car, cdr, cons, quote, cond, atom, eq, and a notation for functions expressed as lists, then you can build all the rest of Lisp out of it.

So, you can write a dialect of Lisp based on Scala, perhaps even as an internal DSL, but that doesn't mean that all Scala programs will belong to this dialect.


问:
Identity and Access Control in Web API vs WCF
Our team is looking to introduce Web API, MVC/ASP.NET implementation in our SOA. I am having a hard time trying to wrap my head around the identity and access control it has compared to WCF.

WCF has Windows, X.509, UserName, and WS-Trust (probably more, but this is what I am familiar with), MVC's Web API seems to only have web application based identity and access control built into it: Web Forms, Windows, and WS-Federation.

Has anyone made Web APIs using MVC that implements the protocols that WCF has?
Should this even be done / am I trying to use Web API in a way it shouldn't be?

答:
In short: WCF has way too much overhead for simple RESTful services. On the other hand, Web API was designed specifically for RESTful services with control over Http Request/Response.

The advantages of having Web API that i can tell straight ahead are:

I like the control over Http Request/Response

It's easy to follow (leveraging MVC patterns), with more tooling will come

I'm in agreement with Dave Ward on this. Check out his blog for more information.

I’ve long held out against pressure to move from ASMX to WCF in
  WebForms projects, because accepting WCF’s complexity primarily only
  rewarded me with less flexible JSON serialization. By contrast, I’ve
  begun converting some of my projects from ASMX to Web API, and have
  been pleased with how easily Web API replaces ASMX.

I believe Microsoft has finally found a good balance between ASMX’s
  simplicity and WCF’s power with Web API.

References on related posts:

WCF Web API: Role based access control with basic authentication

WCF Web API RESTful is not allowed by Access-Control-Allow-Origin

Claims Based Identity & Access Control Guide

Web API or WCF - An Architectural Comparison


问:
Force user to extend class or use configuration
What is better practice: force user to extend abstract class or make class with configuration? Eg. pseudocode:

```<code>ClassA{
 this.name
 this.weight
 this.height
 this.width

 constr(config){
  this.name = config.name
  this.weight = weight
  this.height = height
  this.width = width
 }
}
</code>```

or

```<code>abstract ClassA{
 this.name
 this.weight
 this.height
 this.width
}

ClassB extends ClassA{
 this.name = 'Item'
 this.weight = 12
 this.height = 11
 this.width = 14
}
</code>```

Until now i was using configuration because most libraries use this method, but whats wrong with second method? I recently found that method with extending is producing clearer code but maybe I am missing something?

答:
with your second example in most languages will create new fields in ClassB that are different from those in ClassA (objB.name will be different from ((ClassA)objB).name)

also you shouldn't force your user to inherit from classes if you can avoid it. This is largely because users can make mistakes and forget to initialize a field which leaves the object in a illegal state, or forget to update the implementation when a field gets added/removed

tl;dr: there is less chance of errors when all implementation details of a component are in a single place


答:
Favor composition over inheritence comes into play here, though I'd favor neither if it's possible. Let the class worry about representing itself, construct it with sane defaults and let its consumer worry about how to populate it.

Beyond that, the general arguments for composition over inheritence apply.

Title: Force user to extend class or use configuration

Body:
What is better practice: force user to extend abstract class or make class with configuration? Eg. pseudocode:

```<code>ClassA{
 this.name
 this.weight
 this.height
 this.width

 constr(config){
  this.name = config.name
  this.weight = weight
  this.height = height
  this.width = width
 }
}
</code>```

or

```<code>abstract ClassA{
 this.name
 this.weight
 this.height
 this.width
}

ClassB extends ClassA{
 this.name = 'Item'
 this.weight = 12
 this.height = 11
 this.width = 14
}
</code>```

Until now i was using configuration because most libraries use this method, but whats wrong with second method? I recently found that method with extending is producing clearer code but maybe I am missing something?


问:
Avoiding boilerplate in PHP classes
I am working on a PHP code and as it grows getting more and more tired of repeating the same standard pattern again and again and again:

```<code>class BolerPlate
{
    protected $property1;
    protected $property2;
    ...

    public function __construct ($property1, $property2, ...)
    {
        $this->property1 = $property1;
        $this->property2 = $property2;
        ...
    }
}
</code>```

So I am re-typing here each property name 4 (!) times just to get the standard setup! In each class! It doesn't look elegant nor DRY to me. And re-typing the same names creates more bug opportunities.

I wonder if there is any more elegant way or best practices to get the same setup with a code easier on the eyes :)

EDIT. What I have in mind is some sort of factory method where I can supply the list of properties only once each. Or using variable variables and iterate over all properties?

答:
In short: Traits might be the feature that you look for.

A trait is PHP 5.4’s solution to the lack of multiple inheritance in the language and a way to avoid hierarchical inheritance chains. Another way to think of it is that including traits in your classes is a clean way to keep your code dry without breaking good design principles.

An even more simple way to think about it is: Hey, all that boiler plate code that you copied and pasted everywhere but now you want to change something? well replace it with a trait and call it a day.

Here you are examples and good post on this topic.

Title: Avoiding boilerplate in PHP classes


答:
The two don't have to fight necessarily but generally I'm in agreement that the "OOP CSS" people generally don't have a clue about good programming or good CSS. Some do, but a lot don't.

First of all when people talk about OOP-style CSS, what they're really talking about is a componentization scheme. Not OOP. That they're willing to call it OOP is an argument against it in and of itself. Kool Aid has been mixed and it is being drunk.

Multiple classes used to compose the styles for one element is actually very similar to an inheritance-heavy scheme in OOP. Both are equal parts stupid and needlessly couple concerns by making one set of properties a dependency of far too many things for you to ever change it without running into all sorts of trouble across your entire app. You can have categories of classes define certain subsets in such a way that it does in fact become easy to swap one out for another with little trouble but this puts a pretty hefty burden of competence on typical devs that don't immediately see "OOP CSS" for the oxymoron that it is. But ultimately it's not really designed that way so why do it like that? HTML and CSS work best when you work with how they work, not with how some serious-sounding acronym approach wants them to work.

That said, CSS isn't really designed as semantic either, but it is worth following a similar strategy. Where HTML should mostly describe content, html ID and class names should NOT describe what the CSS or JS bound to them actually do. shiny_red_button IMO is a lousy name for a CSS class. For as design churns, one day your button may not be so big red and shiny even though the button still specifically handles panic and should thus be called 'panic' or perhaps 'panic_btn' if you like denoting the sorts of elements it typically applies to.

I go with the following general rules

Don't describe looks or details of a handler in ID or class names.

Be kinda-semantic. The HTML gives us a general idea of what will be found within. Now get a little more specific as to its design purpose.

Use as few selectors as possible always

The thing that OOP-style CSS thinks it's reacting to is specificity run amuck. Fail. Specificity is not the enemy. It is a tool that you either use well or misuse. So when somebody says "Don't use IDs because they're harder to override" slap them or have them consider this:

#unique_element_container_on_page > a vs. .unique.element.container.on.page > a

If there is one thing that should profoundly offend designers, ui devs, and app/server-oriented devs equally, it's having to !@#$ing count something (like say a java method with 20 optional parameters) to figure out what you need to do next.

IDs are okay.

Said again because I think CSS lint is being silly.

Let context do the polymorphing

HTML is basically taxonomy. Broad categories that fit less broad categories that keep working their way down to specific/unique things. CSS works best when following along with this scheme. Sections may have variations on an even more general theme.

Overriding that theme with a section class followed by whatever descendant is different usually makes a lot more sense than writing a new css component class and dropping that in on the specific element that's different to replace an old one. Intent is more clear and you have fewer dependencies per element to trip on. Except of course when the theme variation isn't really related to where an element is placed. That's one of those rare cases where I'll bust out a comma and add a selector to an existing one and then define its variant properties immediately following with just the new selector. Do enough of that sort of thing and you can white label swap with a simple class change at the top of the page in your HTML.

It is okay to repeat yourself

Use DRY as more of a smell detector than the golden rule with rare exceptions that it is in programming. In CSS it is far more common for two almost like property sets to be like by coincidence, not because their selectors share a purpose. It's better to leave them separated for the day that someone will want to change one and not the other. An ideal CSS file works much like a control-panel where it's reasonably easy to find what you need in order to change something with confidence that you won't also change something else by accident.

Title: Cogent arguments for 'semantic css' over 'object oriented css'

Body:
[Context - I'm a Java developer, having a discussion with a designer who works in the html/css space]

I was having a discussion with a co-worker today about the merits of 'semantic css'.

His response was, "Oh we're not interested in semantic css, we use object oriented css"

I understand what he means, ie that they're using the 'inheritance' properties of css and SASS mixins to describe styles. But I feel like he has not tried to understand 'semantic css'.

I'm trying to construct a cogent argument about why 'object oriented css over semantic css' is flawed.

This is my reasoning so far:

“css isn’t object oriented” https://stackoverflow.com/a/7431746/15441

Write html code with semantic components http://css.dzone.com/articles/object-oriented-css-crap-long

Examples of layout out your page with semantic components http://woork.blogspot.com.au/2008/11/css-coding-semantic-approach-in-naming.html

Examples of non-semantic naming http://css-tricks.com/semantic-class-names/

My question is "what are some cogent arguments explain semantic css to someone who thinks that 'inheritance', 'classes' and 'mixins' make something object oriented and that he doesn't need to worry about good naming?"


问:
What are the alternatives to resx file
I am developing a Windows application and I want to store all the text for labels, radio buttons, buttons, check boxes and column headers of grids at one place. I have tried using a class file, an xml file, a database table and a resource file.

I found that a class file is the best way to store all these texts, but I want to know is there any alternative way? If I am using a class file then I will have to recompile the project if any text changes.

Will a resource file work properly for large amounts data? What about a dictionary or storing data in variables?

答:
In short: It sounds to me like a localization of resources (different types like static labels, text, etc..). Generally speaking, changes in resource file content should not require a re-build of the application.

The dis-advantage to store resources in classes, is that each change/modification will require a re-build of the win-form application.

Will a resource file work properly for large amounts data?

I think the limitation is the file-size limitation of the operating system and that is 4 GB on 32 Bit systems, if I remember correctly. For 64 bit it should be even bigger. Anyway, for the purpose to store the static text, it should be more than enough.

Thus, in my opinion, this should not be done anywhere else if the text will be static.

An alternative approach would be creating a class to control access to your resource files. This class might be used to store the keys to access your resource files and a have strongly typed way to retrieve available resources of the project.

Some references on SE answers on localization and resources:

Resource string location

Globalize an existing Windows Forms application

Using .resx files for global application messages

References from MSDN :

Walkthrough: Localizing Windows Forms

Resource Files (Visual Studio)

Title: What are the alternatives to resx file


问:
What justifies the use of an IDE versus a standard editor?
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?

答: Short learning curve. Thats it.</p>

Body: Short learning curve. Thats it.


答:
When you're just specifying a bunch of simplistic settings (ie, strings, numbers, booleans) inheritance doesn't seem to be the right way to me; multiple instances would be pointless, and as ratcher said, properties defined wouldn't bind to the super-type's. For very low number of options, I'd say constructor arguments like your first example. For higher numbers, perhaps an XML configuration, or even a seperate object type (XYZLibraryConfig).

Not that inheritance for user configuration doesn't have its purposes, if the user is meant to fill in some amount of logic. In response to ratchet's worry of improper extension, I might lean more towards Interfaces, or Abstract classes that require all blanks to be filled in by the user; such that the only way to screw it up is if the customer themselves throws an exception or returns null in the methods they're responsible for.


答:
In C#, you're almost certainly better off using a Resource file (which is an XML file). This gives you the following benefits:

Removes need to re-compile entire solution for changes of text.

Allows management of strings to be done by someone other than the coder (coders aren't necessarily the best people to be writing user error/informational messages).

Allows fairly trivial localisation.

Title: What are the alternatives to resx file

Body:
I am developing a Windows application and I want to store all the text for labels, radio buttons, buttons, check boxes and column headers of grids at one place. I have tried using a class file, an xml file, a database table and a resource file.

I found that a class file is the best way to store all these texts, but I want to know is there any alternative way? If I am using a class file then I will have to recompile the project if any text changes.

Will a resource file work properly for large amounts data? What about a dictionary or storing data in variables?


问:
Understanding unit testing for dynamically changing condition
I was trying to understand how to write unit tests for a few days now. I'm confused with  following scenarios in the existing code.

In first function the max value changes depending on the object created at run time but in the second case it is a constant.

NOTE: The following functions are not related. These are two different scenarios.

SomeFunction1(arg1,....)
{
  if(arg1 > someObject.MaxAllowedValue)
  {
     throw exception;
  }
}
```

<pre class="lang-cs prettyprint-override"><code>SomeFunction2(arg1,....)
{
  if(arg1 > maxAllowedValue)
  {
     throw exception;
  }
}
</code>```

I am trying to test whether the function throws an exception when max value is exceeded.

Does the unit test remain the same in both the cases or is it different?

答: That would depend somewhat on where someObject came from and how its property value changes.  But assuming that someObject.MaxAllowedValue and maxAllowedValue have the same value, the test will remain the same.  Remember, you are testing the behaviour of SomeFunctionX, not the implementation details.


答:
I had a similar requirement before and I stored resources in a .resx file but I have decided to use classes for storing the keys.

For example, say I have resources for banking withdrawal screen.

I have created a simple class on the lines of

```<code>public class BankingWithdrawalResource
{
   public string WithdrawFunds { get; set; }
}
</code>```

I then implemented a class for retrieving resources. My aim was to have a strongly typed way of pulling out resources. I also wanted to make resource retrieval unit testable. I've extracted an interface for retrieving resources: IResource.

Each time I wanted to use resources, I would get an implementation through IoC container.

```<code>var resource = Dependency.Resolve<IResource>();
</code>```

Finally, when it came to using the resource, I would have something on the lines of:

```<code>resource.For<BankingWithdrawalResource>(p => p.WithdrawFunds)
</code>```

In above line, I used lambda expression that allowed me to view all available resources through intellisense.

When it came to unit testing, I would mock IResource and set expectations on it.

For example:

```<code>resourceMock.Expect(a => a.For<BankingWithdrawalResource>(p => p.WithdrawFunds)).Repeat.Once();
</code>```

Also notice that we have extracted an interface for resource retrieval. Because of this, we are now able to store resources anywhere we want. For example:

```<code>public class DatabaseResource : IResource
{
   // Logic to retrieve resources from database
   // Won't cause recompilation
}

public class XmlResource : IResource
{
   // Logic to retrieve resources from xml files
}

public class DefaultResource : IResource
{
   // Will cause recompilation as resources are stored in .resx
}
</code>```

I wrote above from top of my head in notepad, so if you have any problems let me know and I'll add implementation later.

Title: What are the alternatives to resx file

Body:
I had a similar requirement before and I stored resources in a .resx file but I have decided to use classes for storing the keys.

For example, say I have resources for banking withdrawal screen.

I have created a simple class on the lines of

public class BankingWithdrawalResource
{
   public string WithdrawFunds { get; set; }
}

I then implemented a class for retrieving resources. My aim was to have a strongly typed way of pulling out resources. I also wanted to make resource retrieval unit testable. I've extracted an interface for retrieving resources: IResource.

Each time I wanted to use resources, I would get an implementation through IoC container.

var resource = Dependency.Resolve<IResource>();

Finally, when it came to using the resource, I would have something on the lines of:

resource.For<BankingWithdrawalResource>(p => p.WithdrawFunds)

In above line, I used lambda expression that allowed me to view all available resources through intellisense.

When it came to unit testing, I would mock IResource and set expectations on it.

For example:

resourceMock.Expect(a => a.For<BankingWithdrawalResource>(p => p.WithdrawFunds)).Repeat.Once();

Also notice that we have extracted an interface for resource retrieval. Because of this, we are now able to store resources anywhere we want. For example:

public class DatabaseResource : IResource
{
   // Logic to retrieve resources from database
   // Won't cause recompilation
}

public class XmlResource : IResource
{
   // Logic to retrieve resources from xml files
}

public class DefaultResource : IResource
{
   // Will cause recompilation as resources are stored in .resx
}

I wrote above from top of my head in notepad, so if you have any problems let me know and I'll add implementation later.