答:
Another approach you can take is to use mixins.

```<code>    module InteractsWithMailChimp
       def subscribe_email(email, fname, lname)
          Gibbon.list_subscribe(:id => NEWSLETTER_LIST_ID, :email_address => email,
          :merge_vars => {'fname' => fname, 'lname' => lname },
          :email_type => "html",  :double_optin => false, :send_welcome => false)
       end
    end

    Class User
        include InteractsWithMailChimp
    end
</code>```

This approach would give you the benefit of having/using instance variables from the context of the user within the module. The module can be tested in isolation by extending it within any test case. Within the module you can separate the responsibilities for example you can consider that the subscribe/unsubcribe part is a responsibility on its own so you would have:

```<code>    module InteractsWithMailChimp
       class HandlesSubscriptions
           def subscribe_email(email, fname, lname)
              Gibbon.list_subscribe(:id => NEWSLETTER_LIST_ID, :email_address => email,
              :merge_vars => {'fname' => fname, 'lname' => lname },
              :email_type => "html",  :double_optin => false, :send_welcome => false)
           end
       end
    end

    Class User
        include InteractsWithMailChimp::HandlesSubscriptions
    end
</code>```

Within classes that are part of the module if you consider that you would not need any external data there is no problem of making the methods class ones. I like the mixin approach more because it's simple to reuse, it does not need to repeat yourself with the object instantiation and I can name my modules and classes within modules referring exactly to the responsibility they have.
I would still keep these module separate in /lib of course.
For more really nice tips and tricks on how to organize your rails code and have your test run fast you can check out fast rails tests. Hope it helps.

Title: Should I prefer instance methods over class methods in Ruby?

Body:
I'm working on a rails application, and I've been pulling functionality out of my rails code and into pure ruby classes in lib/. I've found myself often writing classes like this:

```<code> class MailchimpIntegration
  def subscribe_email(email, fname, lname)
    Gibbon.list_subscribe(:id => NEWSLETTER_LIST_ID, :email_address => email,
      :merge_vars => {'fname' => fname, 'lname' => lname },
      :email_type => "html",  :double_optin => false, :send_welcome => false)
  end

  def unsubscribe_email(email)
    Gibbon.list_unsubscribe(:id => NEWSLETTER_LIST_ID, :email_address => email)
  end

  def change_details(old_email, email, fname, lname)
    Gibbon.list_update_member(:id => NEWSLETTER_LIST_ID, :email_address => old_email,
      :merge_vars => {'email' => email, 'fname' => fname, 'lname' => lname })
  end

  def get_email_info(email)
    Gibbon.list_member_info(:id => NEWSLETTER_LIST_ID, :email_address => [email])["data"].first
  end
end
</code>```

My question is: Should I change these methods to be class methods?

It seems reasonable to do, as I'll probably end up calling these by just newing up a MailchimpIntegration class each time. However, I generally prefer to have instance methods as they can be more easily stubbed etc, although this seems to be less of an issue in ruby.

I have several classes like this in my system, so I'd be keen to see what people think about this.

Body:
Another approach you can take is to use mixins.

    module InteractsWithMailChimp
       def subscribe_email(email, fname, lname)
          Gibbon.list_subscribe(:id => NEWSLETTER_LIST_ID, :email_address => email,
          :merge_vars => {'fname' => fname, 'lname' => lname },
          :email_type => "html",  :double_optin => false, :send_welcome => false)
       end
    end

    Class User
        include InteractsWithMailChimp
    end

This approach would give you the benefit of having/using instance variables from the context of the user within the module. The module can be tested in isolation by extending it within any test case. Within the module you can separate the responsibilities for example you can consider that the subscribe/unsubcribe part is a responsibility on its own so you would have:

    module InteractsWithMailChimp
       class HandlesSubscriptions
           def subscribe_email(email, fname, lname)
              Gibbon.list_subscribe(:id => NEWSLETTER_LIST_ID, :email_address => email,
              :merge_vars => {'fname' => fname, 'lname' => lname },
              :email_type => "html",  :double_optin => false, :send_welcome => false)
           end
       end
    end

    Class User
        include InteractsWithMailChimp::HandlesSubscriptions
    end

Within classes that are part of the module if you consider that you would not need any external data there is no problem of making the methods class ones. I like the mixin approach more because it's simple to reuse, it does not need to repeat yourself with the object instantiation and I can name my modules and classes within modules referring exactly to the responsibility they have.
I would still keep these module separate in /lib of course.
For more really nice tips and tricks on how to organize your rails code and have your test run fast you can check out fast rails tests. Hope it helps.


问:
Can my company give IP rights away for an application I wrote off hours to another startup?
I am an intern for a health company (unpaid), let's call it Company A and I noticed that they are using a lot of paper form for things that can be done on the computer. Excel files for things that shouldn't be in Excel. So I wanted to improve on my programming and figured that it was the best opportunity to do.

I developed a couple of apps for their use. All these applications were outside company time. One application I did and they love and one of the director has a brother who has a health start up company. He wants me to give over my source code so his brother's company can further develop it and maybe sell it (I am out of the equation).

I have no intention of handing over my code as I put a lot of time outside doing it but I also don't want to burn bridges with anyone in the company. I can't go to the director and tell him "I don't think so".

I am fine with demoing to the brother how it works but the line is giving up my code. If they want to build something like it then they can go right ahead I have no problem with it.

What is the correct way of approaching this and do they have the right to do this to me?

Edit: there is no contract I never signed anything

答:
I am not a lawyer and suggest you contact one.  The following is based on my understanding of the law in some jurisdictions.

I an surprised at the increase in unpaid intern positions.  From what I have seen it allows employers to get something for nothing.  I have also heard reports that they rarely lead to paid work.  If you are an unpaid intern, look of paid work somewhere.

I don't know what, if any contract you signed with the organization.  From a transfer of intellectual property basis, I wouldn't expect them to have a valid contract.  I believe they would need to show your work falls in the category of 'work for hire', which I don't see any evidence of here.   Whatever the law it, it does not prevent an employer from trying to claim the intellectual property rights.

If, as I suspect, your retain the intellectual rights, then your employer does not have the rights and therefore can not give or assign them to anyone.

In my limited experience, even in the presence of a contract stipulating ownership of work done on your own time, you would still retain ownership.  Courts in some jurisdictions will declare the clause unenforceable and give the rights to the employee, not the employer.

ContentLicense: CC BY-SA 3.0


问:
Teaching myself, as a physicist, to become a better programmer
I've always liked physics, and I've always liked coding, so when I got the offer for a PhD position doing numerical physics (details are not relevant, it's mostly parallel programming for a cluster) at a university, it was a no-brainer for me.

However, as most physicists, I'm self taught. I don't have broad background knowledge about how to code in an object oriented way, or the name of that specific algorithm that optimizes the search in some kD tree.

Since all my work so far has been more concerned about the physics and the scientific results, I undoubtedly have some bad habits - more so because my coding is my own, and not really teamwork. I have mostly used C since it is very straightforward and "what you write is what you get" - no need for fancy abstractions. However, I have recently switched to C++ since I'd like to learn more about the power that comes with abstraction, and it's pretty C-like (syntax-wise at least).

How do I teach myself to code in a good, abstract way like a graduate in computer science?

I know my code is efficient, but I want it to be elegant as well, and readable. Keep in mind that I don't have time to read several 1000-page tomes about abstract programming. I need to spend time on actual, physics related research (my supervisor would laugh at me if he knew I spent time thinking about how to program elegantly). How do I assess if my work is also good from a programmer's perspective?

答:
No Royal Road to Software

In ancient times, Euclid was asked a questions like yours by his student King Ptolemy.  His response: "There is no royal road to geometry."

You mention that your supervisor would laugh if he knew how much time you spend trying to write code like a professional developer.  Others answered your questions with a laundry list of things to learn ranging from source control to Design and Analysis of Algorithms.

They fall short of your goal:

"I need to spend time on actual physics"

Concert Pianist or One Man Band?

The world moves too fast for people to dabble.  If you want to be a concert pianist, don't divide your time learning instruments to become a one man band.

My concept for the role of a PhD in physics on medium to large projects is as an idea leader for system definition, expert in theory, subject matter expert during use case creation, and end user / judge for results generated by software artifacts.  Work closely with the best software engineers you can.

How do I assess if my work is also good from a programmer's perspective?

If you want to set the bar high, start here:

Software Architecture in Practice, Len Bass, Paul Clements, Rick Kazman

Look for the chapter "Understanding Quality Attributes".  Beyond code, it considers  usability, modifiable, performance, security, availability, reliability, testability, maintainabiilty, and portablity (not can you carry it, but can you port the design from one platform to another).  All need specific measurable goals.  Similar references include:

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

http://www.sei.cmu.edu/reports/95tr021.pdf

Your Goals vs. C and C++

Like FORTRAN, these are hard and old languages.  Positive indicators for C/C++ include:

Application with hardware, embedded systems.

Existing project you want as a starting points.

There are a lot of people doing web development, data visualization, and big data.  Many are motivated to find or make other languages.  For example, physicist Sir Tim Berners-Lee  made his success with HTML (but is little know for physics).  Evaluate your goal vs. your programming language.

Consider Using Matlab

Matlab has a great installed base, is specialized for math and sciences.  It has tools for data visualization.  It allows scientist and mathematicians to express problems in the problem domain rather than the solution domain.  Matlab makes a Parallel Computing Toolbox and Distributed Computing Server products.

I expect Matlab's success is due to using multidisciplinary teams with people who are experts in physics, math, electronics and instrumentation, operating systems, programming languages, software development, software testing, software architecture and design.  The analogy may be a stretch, but why would you put yourself out there alone, starting with a hammer, chisel, and rasp to make something when you have a 3D printer available?  As Newton might ask, why not stand on someone's shoulders?

ContentLicense: CC BY-SA 4.0


问:
Starting off with web dev with php
I'm currently working with Java / C++. I'm interested in web development and am planning to shift my stream. I heard that PHP is a good platform to start off and also it does not require that much of knowledge in technologies like JSP / Servlets or frameworks like springs / struts / hibernate.

I have basic ideas about HTML and Javascript as well. I have gone through previous posts in SO and found out the relevant resources as well:

http://net.tutsplus.com/tutorials/php/the-best-way-to-learn-php/

http://www.webhostingtalk.com/archive/index.php/t-1028265.html

http://www.killerphp.com/

http://phpforms.net/tutorial/tutorial.html

http://www.php5-tutorial.com/ etc.

Now, my question is: I heard of PHP frameworks like CodeIgniter, Zend Frameworkd and Yii.

Doesn't learning PHP & MySql implicitly makes us aware of these frameworks?

Am I making a good choice in stating with PHP?

Is it a good idea to shift streams?

答:
In my opinion the language choice is not the most influential one. Good practices, knowledge of good software design and architecture, TDD, refactoring they all transcend the choice of a programing language.

Now in regard to your questions:

Learning PHP and Mysql in my opinion doesn't necessarily make you aware of the frameworks. Most of the frameworks out there like Zend, Cake are the traditional MVC frameworks. They where all created with MVC in mind but they use what we call "convention over configuration". And these conventions might differ from one to another: like naming your view, how to pass variables to templates, how to render them and so on. Learning PHP and Mysql would definitely help you dive into their inner workings which could help a lot in the development process.

The last two web apps I've done where one in PHP using Cake and the second Ruby using Ruby on Rails. My suggestion is to choose Ruby and Rails because it's learning curve is leaner and you can get things done way faster. A big plus is the community around Rails which is huge. If you want to implement something I would suggest first checking the gem list, you will be amazed the you will probably find most of the stuff already done by someone else.

It depends on you and your future plans. A programmer in my opinion should be as complete as possible. I think that every developer out there should at least have a basic idea about web development. We should strive to learn and know as much as possible and considering the impact of the web nowadays we should definitely feel somehow obliged to know it's workings. But in the end it all comes down to your judgement.

Hope it helps.

Title: Starting off with web dev with php


问:
How to manage a developer who has poor communication skills
I manage a small team of developers on an application which is in the mid-point of its lifecycle, within a big firm. This unfortunately means there is commonly a 30/70 split of Programming tasks to "other technical work". This work includes:

Working with DBA / Unix / Network / Loadbalancer teams on various tasks

Placing and managing orders for hardware or infrastructure in different regions

Running tests that have not yet been migrated to CI

Analysis

Support / Investigation

Its fair to say that the Developers would all prefer to be coding, rather than doing these more mundane tasks, so I try to hand out the fun programming jobs evenly amongst the team.

Most of the team was hired because, though they may not have the elite programming skills to write their own compiler / game engine / high-frequency trading system etc., they are good communicators who "can get stuff done", work with other teams, and somewhat navigate the complex bureaucracy here. They are good developers, but they are also good all-round technical staff.

However, one member of the team probably has above-average coding skills, but below-average communication skills. Traditionally, the previous Development Manager tended to give him the Programming tasks and not the more mundane tasks listed above. However, I don't feel that this is fair to the rest of the team, who have shown an aptitude for developing a well-rounded skillset that is commonly required in a big-business IT department.

What should I do in this situation? If I continue to give him more programming work, I know that it will be done faster (and conversely, I would expect him to complete the other work slower). But it goes against my principles, and promotes the idea that you can carve out a "comfortable niche" for yourself simply by being bad at the tasks you don't like.

I want to clarify that I'm not trying to address this issue due to a grudge, or that I have a "chip on my shoulder" as was mentioned. I'm looking for advice on how to keep a well-rounded team, which is happy and motivated. By observing the variety of answers to this question, it seems like there are a lot of different opinions on how to achieve this.

答:
I'm a grumpy linux admin who does a lot of scripting, and it has been noticed that I have poor communication skills. I sound a lot like your guy. In fact, that's the only area I get dinged on in performance reviews. Back on the other hand, I'm continuously leading my team in innovation and problem-solving, and have created and led the way to the new platform that we're rolling out and have saved my team a lot of time and my company a lot of money by being allowed to be myself.

My former boss was asked his family/wife AND our company's senior management to leave his position .... simultaneously. He worked tirelessly to balance responsibilities fairly and took on a lot of load himself. During any interaction with anyone outside of the department, if there was a communication misunderstanding that got back to him, he was fast to, ah,  punitively correct it. He was poor at "managing upwards," so our team was the last to get resources until it was an emergency, and then the company overpaid vendors with slick sales pitches for untested hardware without consulting the team that would be using those tools. In an effort to create a "well balanced" team, he micromanaged our task lists and tried to balance out tasks so that team members could improve their skill sets in areas where they weren't great, which resulted in a LOT of broken code or poorly architected implementations. While people other than the author were specifically assigned support tasks for that broken code so that they could "learn" -- the poorly architected implementations, code, and tests created a lot of poor goodwill between team members and actually increased occurrences of the "blame game", which is a fast route to a toxic team state.

My current boss is a calm, collected individual who came in from the junior admin role and has worked his way up. He makes good decisions and relies heavily on team members to set their own priorities. He is an excellent communicator and reacts calmly and in concert with his supervisor to any communication problems, ideas or needs expressed by my team. He "works upwards" tirelessly. He's slow to make major architectural changes, and consults thoroughly with the entire team before making changes to our environment and is comfortable with relying on the specialties of our team members.

Under the new manager, our downtime has dropped to almost zero (which has also dropped the percentage of time that we spend on support tasks from about 40% to about 10%), our team's satisfaction has gone through the roof, and we're on track to have moved from a 'break the bank on new hardware every three to five years' to a continuous acquisition plan that should save the company about a cool million a year over five years. That plan was a grassroots program that never would've happened under the previous manager but was actively pushed to senior management by the new manager and depended on finding a LOT of synergies in the team's skill sets. We've been told informally by the CIO that we're now the only team in the company that really "has their shit together" and that he's going to interfere with our working environment as little as possible and shuffle as many resources towards problem areas that we identify as possible. This has held true, and it's driving our support "cost" even lower, although it has disrupted some other teams' workloads -- but it's driven those teams' support "cost" lower as well.

Look, the place for developers to improve their skill sets is in school or on their own time. The place for them to produce things is on your company's time. The best way to produce things is by producing what they know best. When working in areas where one developer is not comfortable, they should pull in a second developer who is specialized and work as a team, or the specialized developer should write the code and produce documentation and diagrams. Route support tasks to the people that wrote the code. Yes, this increases what we call your "bus factor" -- the likelihood of your department hitting a speed bump if the specialist should get hit by a bus. (Or laid off, or switch jobs, or ...) The truth of it is that your productivity loss from that fear is orders of magnitude higher than the actual loss when a "bus event" happens. What generally happens during a "bus event" is that the inheritor of the specialist's work remakes it in his own image so that he can most effectively support it, generally solving a bunch of problems and lowering time spent on support even further, and life goes on.

Assign things to people who can do them best. Make them support and document their work. Foster their creativity and allow them to focus without distractions or micromanagement. Everything else is management-school BS, which it unfortunately sounds like your company is swimming in. That doesn't mean that your team needs to swim in it, too.

From a company's point of view, a good manager promotes the values of the company while executing tasks according to those values. From an IT employee's point of view, a good manager lets the team do what's right to do as quickly and cleanly as possible and acts as a fecal barrier against senior management pushing values that they learned in weekend MBA classes down the throats of the underlings. You're being a company man, and that might not be the best for your team. The ones with "good" communication skills are just too polite to say it.


问:
How can you learn names of methods or classes of a framework or an API?
I've been programming C++ for a year now. I've gone through the language features and I've written good programs with it, so I decided to move on to OpenGL. At first it seemed confusing. As I kept going through tutorials it appeared to be easier, but I can't remember the names of classes, methods, arguments, etc.

In fact this doesn't just apply for OpenGL; I often get stuck with other frameworks too. I have a program in my head, I know how it would work, but I cannot remember the names of methods or classes to use.

My question here is, in a nutshell, what techniques can you use to memorize those names? Does writing it over and over help you grasp it?

答: If you find it confusing perhaps you can create your own wrapper around the API so you only have to deal with it once. I've never actively gone out to learn off an API.</p>


问:
Is information hiding more than a convention?
In Java, C# and many other strongly-typed, statically checked languages, we are used to write code like this:

```<code>public void m1() { ... }
protected void m2() { ... }
private void m2() { ... }
void m2() { ... }
</code>```

Some dynamically checked languages don't provide keywords to express the level of "privateness" of a given class member and rely on coding conventions instead. Python for example prefixes private members with an underscore:

```<code>_m(self): pass
</code>```

It can be argued that providing such keywords in dynamically checked languages would add little use since it is only checked at runtime.

However, I can't find a good reason to provide these keywords in statically checked languages, either.
I find the requirement to fill my code with rather verbose keywords like protected both annoying and distracting. So far, I have not been in a situation where a compiler error caused by these keywords would have saved me from a bug. Quite in contrary, I have been in situations where a mistakenly placed protected prevented me from using a library.

With this in mind, my question is:

Is information hiding more than a convention between programmers used to define what is part of the official interface of a class?

Can it be used to secure a class' secret state from being attacked? Can reflection override this mechanism? What would make it worthwhile for the compiler to enforce information hiding?

答:
Information hiding evolved from a top-down design philosophy. Python has been called a bottom-up language.

Information hiding is enforced well at the class level in Java, C++ and C#, so it's not really a convention at this level. It's very easy to make a class a "black box", with public interfaces and hidden (private) details.

As you pointed out, in Python it's up to programmers to follow the convention of not using what is intended to be hidden, since everything is visible.

Even with Java, C++ or C#, at some point information hiding becomes a convention. There are no access controls at the highest levels of abstraction involved in more complex software architectures. For example, in Java you can find the use of ".internal." package names. This is purely a naming convention because it's not easy for this kind of information hiding to be enforced via package accessibility alone.

One language that strives to define access formally is Eiffel. This article points out some other information-hiding weaknesses of languages such as Java.

Background: Information hiding was proposed in 1971 by David Parnas. He points out in that article that use of information about other modules can "disastrously increase the connectivity of the system structure." According to this idea, lack of information hiding can lead to tightly coupled systems that are hard to maintain. He continues with:

We wish to have the structure of the system determined by the designers explicitly before programming begins, rather than inadvertently by a programmer's use of information.


问:
What are the various branches of the C++ language out there?
Last time I tried to use C++ several years ago I remember having to include different libraries between different IDEs even though I was using the same operating system, which left me somewhat confused about the C++ language.

Are there different standardizations of the C++ language? And if so, what branches of the language exist out there? Is the syntax and/or library names for each standardization different between operating systems? Also, What is primary standardization used nowadays?

答:
You can read about c++ in c++ wiki.

Are there different standardizations of the C++ language? And if so, what branches of the language exist out there?

There are 3 major versions of c++ : c++11, c++03 and c++98.

c++11 is the latest version, and there are features are still not supported in compilers.

Is the syntax and/or library names for each standardization different between operating systems?

No, c++ has the same syntax defined by ISO document (ISO/IEC 14882:2011 for c++11). What differs between OSes is support for various features between compilers on these OSs, and their bugs.

Also, What is primary standardization used nowadays?

That depends on the available compiler, it's features and the organization where you work. Some compilers (like for example TI's c++ compiler) supports only c++98. Some organizations are slow in making big changes (like changing compiler version) and do not allow c++11 features.


问:
In C and C++, what methods can prevent accidental use of the assignment(=) where equivalence(==) is needed?
In C and C++, it is very easy to write the following code with a serious error.

```<code>char responseChar = getchar();
int confirmExit = 'y' == tolower(responseChar);
if (confirmExit = 1)
{
    exit(0);
}
</code>```

The error is that the if statement should have been:

```<code>if (confirmExit == 1)
</code>```

As coded, it will exit every time, because the assignment of the confirmExit variable occurs, then confirmExit is used as the result of the expression.

Are there good ways to prevent this kind of error?

答: I agree with everyone saying "compiler warnings" but I want to add another technique: Code reviews. If you have a policy of reviewing all code that gets committed, preferably before it's committed, then it's likely this kind of thing will be caught during review.</p>


问:
Story points for bug fixing tasks: Is it suitable for Scrum?
I'm just wondering if we should assign story points to bug fixing tasks or not. JIRA, our issues-tracking software, does not have story point field for Bug type issues (it's only for Storys and Epics).

Should we add the Bug issue type to the applicable issue types of the Story Points field?  What are the pros and cons? Would it be suitable for Scrum?

答:
Estimating stories is based on the notion that, with time, a team earns experience in resolving them. With it accuracy is improved and velocity can be established to measure a teams speed. A perfect methodology for establishing reliable prognoses for future sprints.

Bugs are a fact of life for a software development company. While I agree that bugs should all be caught during the development of a story, accepting that this cannot be achieved at all times, should be something that every team should plan for. Instead of stubbornly thinking that the process should rule the team, it should be the other way round.

Of course, bug or story, from the business side it does not matter what the team is dealing with. Both can produce an equal amount of value for the product owner.

In our team we have experimented with some techniques for estimating bugs:

Estimating completely unknown bugs

Only estimating bugs which were already analyzed

Allotting time for bug fixing and not estimating bugs, but rank them instead solely based on business value

With 1. we have failed misearably. For most bugs we have found 90% of the time is spent on the bug analysis. After that the bug fix can be estimated in the same way as a story. By planning the bugs into a sprint we made the mistake that the unknown scope impacted story resolution up until the point where almost every sprint we did this way failed.

Based on the 90/10 ratio (analysis to bug fixing) estimation technique option 2. did mean that we had to plan for analysis which was not something that was covered for sprint planning (we had learned from option 1, but had no real solution how to go on with analyzed bugs). The result was that bug analysis was not done since a sprint focused on the planned items instead. The team did not have time to focus on bugs from the backlog. So eventually they did not get done either.

By embracing uncertainty we have now settled on option 3. We have split up the product backlog into a regular story/task part that can be estimated by the team using story points and a bug backlog. In the bug backlog the product owner ranks bugs based on business value and very rough team judgement. The team allows for allotting a chunk of time during a sprint that it can spend on focusing on bugs. The product owner does not know the exact outcome as it was not possible to plan that anyway before. The ratio of bug backlog versus regular backlog can be adjusted for each sprint depending on the current status of each backlog and the importance and business value of the content.

By taking out the uncertainty it did free up the team again. Sprints were not compromised by unknown bugs. By separating bugs into a different backlog both increased team's regular sprint focus and made us finish bugs which contained significant business value as well.

So it depends whether story points are suitable for you. I would try to estimate bugs using story points first. If that fails try my option 3. It has made our (over 30 sprint old) team focus on older bugs again which contain great business value. It has also freed us from trying to deliver something which the team simply cannot estimate. It was embracing the unknown that got us closer to the reality and also made our sprints successful again while delivering a big chunk (based on the bug to story ratio) of business value through bug fixes. The ratio we used recently was 50/50.


问:
How important is it to learn makefiles?
I work in c++ mostly as a hobby (I'm still in school and therefor don't have a real job). The IDEs generate the makefile for me and so I'm wondering if it's worth learning how to make them myself. By "worth learning" I mean, should I drop everything and learn how to write them before continuing to learn c++? Is learning them going to be really necessary? If so, should I learn about them (general syntax and understanding how they work etc.) or really learn how to write them?</p>

答:
Makefiles are important on UNIX systems (e.g. AIX, Linux, OS X).  However, I think that their absolute "you gotta know it" importance has diminished in recent years. For example, you don't really find them in Windows development (Visual Studio, etc.) and XCode (on OS X) uses a different system altogether.  I'm not much into Java, but there I think they use ant files and whatnot.

There is a very cool system called CMake that generates native build files for the operating system that you happen to be running on. For example, if you write your project specification in CMake, then you can create a Visual Studio build project on Windows, an XCode project on Mac, and a Makefile on Linux. In a way, CMake replaces autoconf and automake.

I usually create CMake files for my "big projects" but I know Make in case I want to write a quick "just get it done" Makefile.  It's good for your cultural literacy, because there are tons and tons of software libraries that use Makefiles, and you will inevitably need to edit the specific compilers and library locations. But you will find that big projects (like KDE) are migrating toward CMake and the like since Make does have some limitations that rear their ugly head when projects get complicated.

Title: How important is it to learn makefiles?


答: Being able to successfully use make or something like it lets you check the "understands how to model the dependencies between parts of a program composed of more than one module" box.

Title: How important is it to learn makefiles?

Body: I work in c++ mostly as a hobby (I'm still in school and therefor don't have a real job). The IDEs generate the makefile for me and so I'm wondering if it's worth learning how to make them myself. By "worth learning" I mean, should I drop everything and learn how to write them before continuing to learn c++? Is learning them going to be really necessary? If so, should I learn about them (general syntax and understanding how they work etc.) or really learn how to write them?</p>


答:
First, raising your warning levels never hurts.

If you do not want your conditional to test the result of an assignment within the if statement itself, then having worked with a lot of C and C++ programmers over the years, and having never heard that comparing the constant first if(1 == val) was a bad thing, you could try that construct.

If your project leader approves of your doing this, don't worry about what other people think. The real proof is whether you or someone else can make sense of your code months and years from now.

If you intention was to test the result of an assignment, however, then using higher warnings might [probably would have] caught the assignment to a constant.

Title: In C and C++, what methods can prevent accidental use of the assignment(=) where equivalence(==) is needed?

Body:
In C and C++, it is very easy to write the following code with a serious error.

```<code>char responseChar = getchar();
int confirmExit = 'y' == tolower(responseChar);
if (confirmExit = 1)
{
    exit(0);
}
</code>```

The error is that the if statement should have been:

```<code>if (confirmExit == 1)
</code>```

As coded, it will exit every time, because the assignment of the confirmExit variable occurs, then confirmExit is used as the result of the expression.

Are there good ways to prevent this kind of error?


问:
Scheme vs Haskell for an Introduction to Functional Programming?
I am comfortable with programming in C and C#, and will explore C++ in the future. I may be interested in exploring functional programming as a different programming paradigm. I am doing this for fun, my job does not involve computer programming, and am somewhat inspired by the use of functional programming, taught fairly early, in computer science courses in college. Lambda calculus is certainly beyond my mathematical abilities, but I think I can handle functional programming.

Which of Haskell or Scheme would serve as a good intro to functional programming? I use emacs as my text editor and would like to be able to configure it more easily in the future which would entail learning Emacs Lisp. My understanding, however, is that Emacs Lisp is fairly different from Scheme and is also more procedural as opposed to functional.

I would likely be using "The Little Schemer" book, which I have already bought, if I pursue Scheme (seems to me a little weird from my limited leafing through it). Or would use the "Learn You a Haskell for Great Good" if I pursue Haskell. I would also watch the Intro to Haskell videos by Dr Erik Meijer on Channel 9.

Any suggestions, feedback or input appreciated.

Thanks.

P.S. BTW I also have access to F# since I have Visual Studio 2010 which I use for C# development, but I don't think that should be my main criteria for selecting a language.

答:
In one of the answers you received to your question, I found this link quite interesting, because it gives you a a taste of Haskell and Scheme.

In addition to that nifty link, here is my take on your question.

If you're coming from an imperative programming background, you may wind up putting a lot of effort into learning functional programming. I would make sure that learning experience is not empty. That is that you can apply it to your current or next job or that it will help you in some other way.

There are a lot of good languages out there. The Scala people would extol their language, as would the Clojure and CL folks. Even Pythonistas claim laziness. Other people who answered you suggested ML. Amit Rathore who wrote Clojure in Action might even suggest you learn Haskell.

You mentioned Windows and F#. Will that help you in your current position? I don't know anything about F#. Is it functional enough? I ask that, because IMHO Python has functional constructs, but it's not like programming in Clojure.

To summarize, learn a functional language that is "really" functional and in doing so makes best sense for your situation.

OwnerDisplayName: haziz


问:
Low Coupling: Single Responsibility Principle vs Cohesion
I've read several articles on SRP and cohesion, and they seem to contradict each other as far as low coupling is concerned.

Articles on cohesion argue that putting closely related responsibilities together in a class Highly_Cohesive_Class reduces coupling, while articles on SRP would argue that we'd reduce coupling by removing these closely related responsibilities from class Highly_Cohesive_Class into separate classes ( such that each class only has single responsibility/reason to change ).

Don't the two claims contradict each other? Namely,

BTW - I'm aware of the fact that class adhering to SRP principle is also considered highly cohesive class, but in this post the term highly cohesive refers to a class that has several closely related responsibilities.

答:
I think the confusion is that high cohesion does not necessarily mean you want to put all of the "closely related responsibilities" in one class, but rather that all of the items in a class should correspond to closely related responsibilities.

For example, if you have a Kitchen class, you wouldn't want bathroom logic in it; however, you don't HAVE to also have oven and kitchen sink logic in it too, just because they are related.  Although it is a kitchen appliance, the Oven probably deserves its own class, and would end up relating to the Kitchen through composition.  Likewise the KitchenSink would be related to the Kitchen through composition.

So, look at a highly cohesive as NOT HAVING unrelated logic in it, and look a SRP as the call to delegate responsibilities to objects that serve that one responsibility.


答:
I have not been in a situation where a compiler error caused by these keywords would have saved me from a bug.

It's not so much to save application authors from bugs as to let library authors decide which parts of their implementation they're committing to maintaining.

If I have a library

```<code>class C {
  public void foo() { ... }

  private void fooHelper() { /* lots of complex code */ }
}
</code>```

I may want to be able to replace foo's implementation and possibly change fooHelper in radical ways.  If a bunch of people have decided to use fooHelper despite all the warnings in my documentation then I may not be able to do that.

private lets library authors break libraries into manageable sized methods (and private helper classes) without the fear that they'll be forced to maintain those internal details for years.

What would make it worthwhile for the compiler to enforce information hiding?

On a side note, in Java private is not enforced by the compiler, but by the Java bytecode verifier.

Can reflection override this mechanism? What would make it worthwhile for the compiler to enforce information hiding?

In Java, not only reflection can override this mechanism.  There are two kinds of private in Java.  The kind of private that prevents one outer class from accessing another outer class's private members which is checked by the bytecode verifier, but also privates that are used by an inner class via a package-private synthetic accessor method as in

```<code> public class C {
   private int i = 42;

   public class B {
     public void incr() { ++i; }
   }
 }
</code>```

Since class B (really named C$B) uses i, the compiler creates a synthetic accessor method that allows B to access C.i in a way that gets past the bytecode verifier.  Unfortunately, since ClassLoader allows you to create a class from a byte[], it's fairly simple to get at the privates that C has exposed to inner classes by creating a new class in C's package which is possible if C's jar has not been sealed.

Proper private enforcement requires coordination between the classloaders, bytecode verifier, and the security policy which can prevent reflective access to privates.

Can it be used to secure a class' secret state from being attacked?

Yes.  "Secure decomposition" is possible when programmers can collaborate while each preserving the security properties of their modules -- I don't have to trust the author of another code module not to violate the security properties of my module.

Object Capabilities languages like Joe-E use information hiding and other means to make secure decomposition possible:

Joe-E is a subset of the Java programming language designed to support secure programming according to object-capability discipline. Joe-E is intended to facilitate construction of secure systems, as well as to facilitate security reviews of systems built in Joe-E.

The paper linked from that page gives an example of how private enforcement makes secure decomposition possible.

Providing secure encapsulation.

Figure 1. An append-only logging facility.

```<code>public final class Log {
  private final StringBuilder content;
  public Log() {
    content = new StringBuilder();
  }
  public void write(String s) {
    content.append(s);
  }
}
</code>```

Consider Fig. 1, which illustrates how one might build an append-only log facility.
  Provided that the rest of the program is written in Joe-E,
  a code reviewer can be conﬁdent that log entries can only
  be added, and cannot be modiﬁed or removed. This review
  is practical because it requires only inspection of the Log
  class, and does not require review of any other code. Consequently, verifying this property requires only local reasoning about the logging code.

Title: Is information hiding more than a convention?

Body:
In Java, C# and many other strongly-typed, statically checked languages, we are used to write code like this:

```<code>public void m1() { ... }
protected void m2() { ... }
private void m2() { ... }
void m2() { ... }
</code>```

Some dynamically checked languages don't provide keywords to express the level of "privateness" of a given class member and rely on coding conventions instead. Python for example prefixes private members with an underscore:

```<code>_m(self): pass
</code>```

It can be argued that providing such keywords in dynamically checked languages would add little use since it is only checked at runtime.

However, I can't find a good reason to provide these keywords in statically checked languages, either.
I find the requirement to fill my code with rather verbose keywords like protected both annoying and distracting. So far, I have not been in a situation where a compiler error caused by these keywords would have saved me from a bug. Quite in contrary, I have been in situations where a mistakenly placed protected prevented me from using a library.

With this in mind, my question is:

Is information hiding more than a convention between programmers used to define what is part of the official interface of a class?

Can it be used to secure a class' secret state from being attacked? Can reflection override this mechanism? What would make it worthwhile for the compiler to enforce information hiding?

Body:
I have not been in a situation where a compiler error caused by these keywords would have saved me from a bug.

It's not so much to save application authors from bugs as to let library authors decide which parts of their implementation they're committing to maintaining.

If I have a library

class C {
  public void foo() { ... }

  private void fooHelper() { /* lots of complex code */ }
}

I may want to be able to replace foo's implementation and possibly change fooHelper in radical ways.  If a bunch of people have decided to use fooHelper despite all the warnings in my documentation then I may not be able to do that.

private lets library authors break libraries into manageable sized methods (and private helper classes) without the fear that they'll be forced to maintain those internal details for years.

What would make it worthwhile for the compiler to enforce information hiding?

On a side note, in Java private is not enforced by the compiler, but by the Java bytecode verifier.

Can reflection override this mechanism? What would make it worthwhile for the compiler to enforce information hiding?

In Java, not only reflection can override this mechanism.  There are two kinds of private in Java.  The kind of private that prevents one outer class from accessing another outer class's private members which is checked by the bytecode verifier, but also privates that are used by an inner class via a package-private synthetic accessor method as in

 public class C {
   private int i = 42;

   public class B {
     public void incr() { ++i; }
   }
 }

Since class B (really named C$B) uses i, the compiler creates a synthetic accessor method that allows B to access C.i in a way that gets past the bytecode verifier.  Unfortunately, since ClassLoader allows you to create a class from a byte[], it's fairly simple to get at the privates that C has exposed to inner classes by creating a new class in C's package which is possible if C's jar has not been sealed.

Proper private enforcement requires coordination between the classloaders, bytecode verifier, and the security policy which can prevent reflective access to privates.

Can it be used to secure a class' secret state from being attacked?

Yes.  "Secure decomposition" is possible when programmers can collaborate while each preserving the security properties of their modules -- I don't have to trust the author of another code module not to violate the security properties of my module.

Object Capabilities languages like Joe-E use information hiding and other means to make secure decomposition possible:

Joe-E is a subset of the Java programming language designed to support secure programming according to object-capability discipline. Joe-E is intended to facilitate construction of secure systems, as well as to facilitate security reviews of systems built in Joe-E.

The paper linked from that page gives an example of how private enforcement makes secure decomposition possible.

Providing secure encapsulation.

Figure 1. An append-only logging facility.

public final class Log {
  private final StringBuilder content;
  public Log() {
    content = new StringBuilder();
  }
  public void write(String s) {
    content.append(s);
  }
}

Consider Fig. 1, which illustrates how one might build an append-only log facility.
  Provided that the rest of the program is written in Joe-E,
  a code reviewer can be conﬁdent that log entries can only
  be added, and cannot be modiﬁed or removed. This review
  is practical because it requires only inspection of the Log
  class, and does not require review of any other code. Consequently, verifying this property requires only local reasoning about the logging code.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答: I'm from Brazil, and in my last job, some guys didn't speak english, so we had to write things in portuguese, but most of the people wrote in english.</p>


问:
How does a garbage collector prevent the whole memory from being scanned on every collect?
Some (at least Mono's and .NET's) garbage collectors have a short term memory area which they scan often, and a secondary memory area which they scan less often. Mono calls this a nursery.

To find out which objects can be disposed of, they scan all objects starting from roots, the stack and the registers and dispose all objects that aren't being referenced anymore.

My question is how they prevent all in use memory from being scanned on every collect? In principle, the only way to find out what objects aren't in use anymore is to scan all objects and all their references. However, this would prevent the OS from swapping out memory even though it isn't in use by the application and feels like a huge amount of work that needs to be done, also for "Nursery Collection". It doesn't feel like they're winning much by using a nursery.

Am I missing something or is the garbage collector actually scanning every object and every reference every time it does a collection?

答: To find out what nursery objects are still live, the collector only needs to scan the the root set and any old objects that have been mutated since the last collection, since an old object that has not been recently mutated cannot possibly point to a young object. There are different algorithms for maintaining this information at varying levels of precision (from an exact set of mutated fields to a set of pages where mutation may have occurred), but they all generally involve some sort of write barrier: code that runs on every reference-typed field mutation that updates the GC's bookkeeping.


问:
How much more should I charge for freelance project source code?
Currently I'm working as a freelancer, and for the first time a faced a client who wants the source code too.

This client owns a software development company, and wants to have rights over the source code, but that I keep my rights too. That means that they can use my code to make similar applications using my code for different customers and the same applies for me.

How much more should I charge my client?

答: If you've got a business model based on cranking out minor variations on a body of code you've developed over years, I'd say charge the total development cost for all your stock code.  I bet the customer decides either he doesn't need you, or doesn't need your source code.</p>


答:
Here are a couple of ideas:

Estimate (guess) how much money you are likely to make using the code in the future.  Multiply that by something and charge them that.

Offer the source code on the condition that they do not sell products / services using it, and that they don't compete with you.

Instead of money up front, ask for a percentage of their gross income from any software / services they provide based on your product.

In all cases, get a good lawyer to advise you and help you draw up the contracts.  There's a fair likelihood that your customer is one of those business who will "screw" you if it gets the chance.  (The fact that the customer is even asking means that he/she/they think they can make more money than you will charge them.)

Your starting point should be that you already have a business model that is working for you.  If there is a risk that this customer is going to undermine your business model, then you need to be adequately compensated.

Title: How much more should I charge for freelance project source code?

Body:
Currently I'm working as a freelancer, and for the first time a faced a client who wants the source code too.

This client owns a software development company, and wants to have rights over the source code, but that I keep my rights too. That means that they can use my code to make similar applications using my code for different customers and the same applies for me.

How much more should I charge my client?


问:
Who should initialize dependencies in a TDD application?
I'm trying to learn implementing TDD with mocking/fake objects. One of the questions I have is how to initialize a dependency in an application which implements TDD? An example from this article
Beginning Mocking With Moq 3 shows:

```<code>public class OrderWriter
{
    private readonly IFileWriter fileWriter;

    public OrderWriter(IFileWriter fileWriter)
    {
        this.fileWriter = fileWriter;
    }

    public void WriteOrder(Order order)
    {
        fileWriter.WriteLine(String.Format("{0},{1}", order.OrderId, order.OrderTotal));
    }
}
</code>```

In this example, the constructor takes an IFileWriter parameter, I suppose because you want to supply the real file writer in case of the actual application, and the fake one for unit test. My question is, in the real application, who will supply this parameter? I suppose it will be the caller of this application. What if it has dependency as well in the constructor? Will the caller code be responsible for that too?

Maybe the better way is to use factory. How would this factory work? And how  will the factory be distributed? Will it be in the constructor parameter like in the above manner?

答:
What you're looking for is an IoC container to autowire all your objects at application startup. Take a look at Ninject, it has a very simple example on the front page. (It's also a good product and ... well, ninjas!)

As a general rule, you should attempt to resolve all of your top-level objects (eg. Page in ASP.NET, Controller in MVC for ASP.NET, Form in Winforms) directly from the IoC container and let it wire up ALL your dependencies through constructor injection. There will be times when you have to force it to resolve a lower-level item -- this is known as using it as a Service Locator -- but this should generally be avoided as they are tricky (but not impossible) to test, and create an API that can be confusing for the consumer, if that isn't you.

ASP.NET for MVC has, since v3, been specifically designed to abstract away the IoC container from the rest of your code while allowing you to auto-inject into any top-level class (Controller, View, Filter, etc) through the DependencyResolver class. Other .NET frameworks take a bit more effort, but it's possible if you Google around.

There is a book on the subject called Dependency Injection in .NET. I haven't read it personally, but I've heard good things.


问:
Can a compiled C++11 library (lib,dll,etc.) be linked in older C++ compilers?
Could older C++ compilers (e.g. VS2008 and gcc3.4) link with external libraries written in C++11?

My thought is that the C++11 .lib files are just byte code at this stage, and it shouldn't bother the older compilers how it was generated, as long as it is somehow resolvable and callable.

I'm developing a small library whose API should still support C++03 users. So, looking forward, I'm wondering whether it's ok to implement my library using helpful features like std::unique_ptr and such, or do I have to just stick with boost::?

答:
Sounds like you want to write a new library for others to use, and that you would like to use C+11 as your implementation language. There are a number of issues to consider:

by introducing a new version of C++ you will introduce the need to deploy the new C++ runtime libraries with your library, is that OK?

you should not use new C+11 types in your public interface, otherwise they will not be able to call it.

In general, you should avoid complex types, such as unique_ptr, even vector, etc. Unless you are distributing your library as source code, the layout of the objects in your library may differ from the layout in the client code. Stick with simple types that have no risk of object layout variations.


问:
why no hasLock/testLock on mutexes
looking through the docs of posix' pthread_mutex_t and window's mutex and CRITICAL_SECTION I noticed there is no easy way of checking whether the current thread holds a specific mutex

posix' pthread_mutex_t can be tested when it's not reentrant but that is only a artifact of a non-reentrant mutex

ofcourse checking whether another thread holds a mutex is trivial with trylock

java does allow checking whether the current (and only current) thread holds an object monitor with Thread.holdsLock(Object) which is advised to only be used for debugging

likewise the interface of java.util.concurrent.locks.Lock in also doesn't provide any checking method (the implementation ReentrantLock however does with ReentrantLock.isHeldByCurrentThread())

I can imagine that this can be quite easily implemented alongside any other lock (and is even required when implementing a reentrant mutex)

all it would require is a unique handle for each thread (already available in threading libraries or could even be the TLS pointer whichever is smaller) and at most 2 extra fields (one for the handle and one for the holdcount)

when locking: after the lock is acquired increment the holdcount and set the handle to the current thread handle

when unlocking: before unlocking decrement the holdcount and set the handle to nil only when the holdcount is now 0

when testing: get the handle and compare it to the current thread's handle

this may be possible without any membarriers as long as a simultaneous write doesn't mangle the bits of the read in a such way that a handle is read that wasn't being written (i.e. the reading thread's handle)

the only race conditions possible are in #3 (the rest happens when the lock is held) and may be irrelevant depending on the memory model given the size of the read value (one word) (edit: if a atomic read/write scheme is used this is even solved entirely)

the holdcount is not even be necessary when the mutex is not reentrant and you're not making it reentrant

EDIT2: I want to clarify that the hasLock would only be used for debugging purposes (asserts) for example to ensure that a method that needs a lock held by the caller actually has it

as for the race condition being irrelevant:

first requirement is that you need a way to write and read concurrently in a way that you would only get values that were actually written

second the test handle == currentHandle would treat both nil and the handle of another thread the same way

the only way that currentHandle would be equal to handle is when the current thread has written it during locking

答:
There's absolutely no reason, from a functionality standpoint, not to have included a test-and-lock functionality, and in previous jobs (I was an AIX kernel developer) I've used that to great effect.

Implementation is trivial -- any architecture which supports compare-and-swap operations can atomically test for a lock being set and acquire the lock at the same time.  If the compare-and-swap works, you have the lock and no one else can acquire it until you compare-and-swap back to the unlocked state.  If it fails, someone else has the lock.

In Java, it's fairly simple.  Declare a Long variable.  Synchronize on that variable and check to see if it is zero (unlocked) or non-zero.  If it is zero, set the value to Thread.currentThread().getId(), and return true.  If it is non-zero, set it to false.  When you're done, reverse the process -- synchronize on the variable, set its value to zero and you're done.

What you do with a locking scheme that supports test-and-lock type functionality is up to you.  Saying "It's bad -- don't do it!" is naive.

Title: why no hasLock/testLock on mutexes


答:
As long as you have the rights to use the code yourself on future projects, get as much as you can and cash the check. Speaking from well over 30 years experience, source code rights are mostly bullsh*t. It sounds like a big deal, but it isn't.

If it's anything more than a toy program, they're probably going to have to come back to you for any substantial changes. Back in the 80's I sold DEC non-exclusive source rights to a search engine for well over $100,000. 18 months later they were back wanting over $50,000 in custom mods (based on my hourly rate). Why? Because they didn't have the talent available to come up to speed on 300,000+ LOC and make the mods in the time frame they needed them.

Bottom line: money for non-exclusive source rights is found money. Take it and take a vacation.


问:
What do you call "X <= $foo <= Y" comparison?
While writing a Perl statement like if ( $foo >= X && $foo <= Y ) yet again, I wondered why many programming languages do not support the more comfortable form if ( X <= $foo <= Y ) and what this is called.  I came up with "3-legged comparison" but no results when searching for it. By the way there is also the "element-of-set" form if ( $foo in X..Y ) which I only consider more readable when provided via a short keyword.

Is there a term for X <= $foo <= Y comparison?  Which languages support it?

答:
SQL has a native bounds/range check operator:

```<code>SELECT * FROM foo WHERE foo.bar BETWEEN 1 AND 100
</code>```

Checking whether a value is within a certain range makes sense in SQL due to the algebraic nature of relational databases.

When it comes to programming languages though, there's an  order of operations and ( X <= $foo <= Y ) would normally be interpreted as ( ( X <= $foo ) <= Y ) ), which is a quite different than ( $foo >= X && $foo <= Y ). To get a sweet & simple range check operator we would have to tell the parser to ignore the order of operations for this very specific case, and that would go against the principle of least astonishment.

Not worth the trouble and the potential confusion for something that's of extremely little benefit, just syntactic sugar really. If you find yourself doing range checks very often and don't care for typing a few extra characters, you can always write a short function to take care of the comparisons for you.

Body:
SQL has a native bounds/range check operator:

SELECT * FROM foo WHERE foo.bar BETWEEN 1 AND 100

Checking whether a value is within a certain range makes sense in SQL due to the algebraic nature of relational databases.

When it comes to programming languages though, there's an  order of operations and ( X <= $foo <= Y ) would normally be interpreted as ( ( X <= $foo ) <= Y ) ), which is a quite different than ( $foo >= X && $foo <= Y ). To get a sweet & simple range check operator we would have to tell the parser to ignore the order of operations for this very specific case, and that would go against the principle of least astonishment.

Not worth the trouble and the potential confusion for something that's of extremely little benefit, just syntactic sugar really. If you find yourself doing range checks very often and don't care for typing a few extra characters, you can always write a short function to take care of the comparisons for you.


答:
I'd call it an n-ary comparison.

Operators that work on arbitrary numbers of operands are called "n-ary" operators:

n-ary

From a mathematical point of view, a function of n arguments can always be considered as a function of one single argument which is an element of some product space. However, it may be convenient for notation to consider n-ary functions, ...

The same is true for programming languages, where functions taking several arguments could always be defined as functions taking a single argument of some composite type such as a tuple, or in languages with higher-order functions, by currying.

Binary means 2-ary.

...

n-ary means n operands (or parameters), but is often used as a synonym of "polyadic".

Python has an n-ary < operator.  Section 5.6 of the language docs says:

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:

Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

Title: What do you call "X <= $foo <= Y" comparison?

Body:
While writing a Perl statement like if ( $foo >= X && $foo <= Y ) yet again, I wondered why many programming languages do not support the more comfortable form if ( X <= $foo <= Y ) and what this is called.  I came up with "3-legged comparison" but no results when searching for it. By the way there is also the "element-of-set" form if ( $foo in X..Y ) which I only consider more readable when provided via a short keyword.

Is there a term for X <= $foo <= Y comparison?  Which languages support it?


问:
How essential is it to make a service layer?
I started building an app in 3 layers (DAL, BL, UI) [it mainly handles CRM, some sales reports and inventory].

A colleague told me that I must move to service layer pattern, that developers came to service pattern from their experience and it is the better approach to design most applications. He said it would be much easier to maintain the application in the future that way.

Personally, I get the feeling that it's just making things more complex and I couldn't see much of a benefit from it that would justify that.

This app does have an additional small partial ui that uses some (but only few) of the desktop application functions so I did find myself duplicating some code (but not much). Just because of some code duplication I wouldn't convert it to be service oriented, but he said I should use it anyway because in general it's a very good architecture, why programmers are so passionate about services??

I tried to google on it but I'm still confused and can't decide what to do.

答:
I agree with you. There is no need to include one more layer if you are using a single UI.

DAL,BL and UI/Controller are good combination to design an application. If you are planning to go with a single UI, there is no need to prepare an extra layer. Including 1 more layer into application only increases development efforts/time.

Another schenerio is to use multiple UIs in your application, it is good to have a service layer to handle UIs in this case.

Stack Overflow : Discussion on service layer pattern


答:
Martin Fowler's book "Patterns of Enterprise Architecture" states:

The easier question to answer is probably when not to use it. You probably don't need a Service Layer if your application's business logic will only have one kind of client - say, a user interface - and it's use case responses don't involve multiple transactional resources. [...]

But as soon as you envision a second kind of client, or a second transactional resource in use case responses, it pays to design in a Service Layer from the beginning.

The benefits a Service Layer provides is that it defines a common set of application operations available to different clients and coordinates the response in each operation. Where you have an application that has more than one kind of client that consumes its business logic and has complex use cases involving multiple transactional resources - it makes sense to include a Service Layer with managed transactions.

With CRM, Sales and Inventory there will be a lot of CRUD-type use cases of which there is almost always a one-to-one correspondence with Service Layer operations. The responses to creation, update or deletion of a domain object should be coordinated and transacted atomically by Service Layer operations.

Another benefit of having a Service Layer is that it can be designed for local or remote invocation, or both - and gives you the flexibility to do so. The pattern lays the foundation for encapsulated implementation of an application's business logic and invocation of that logic by various clients in a consistent manner. This means you also reduce/remove duplication of code, as your clients share the same common services. You can potentially reduce maintenance costs too - as when your business logic changes, you (generally) only need to change the service, and not each of the clients.

In summary, it's good to use a Service Layer - more-so I think in your example you have provided as it sounds like you have multiple clients of business logic.

Title: How essential is it to make a service layer?

Body:
I started building an app in 3 layers (DAL, BL, UI) [it mainly handles CRM, some sales reports and inventory].

A colleague told me that I must move to service layer pattern, that developers came to service pattern from their experience and it is the better approach to design most applications. He said it would be much easier to maintain the application in the future that way.

Personally, I get the feeling that it's just making things more complex and I couldn't see much of a benefit from it that would justify that.

This app does have an additional small partial ui that uses some (but only few) of the desktop application functions so I did find myself duplicating some code (but not much). Just because of some code duplication I wouldn't convert it to be service oriented, but he said I should use it anyway because in general it's a very good architecture, why programmers are so passionate about services??

I tried to google on it but I'm still confused and can't decide what to do.


问:
Relative Scoring system - How to solve this?
I am trying to assign scores to phone's specifications to calculate a final rating score for each phone. </p>

<p>However, when I was scoring based on megapixels, I found that one of the phones 'A' has a 41MP camera. But all other phones have 8MP or less, which is pretty good for a phone. Right now, when I grade relatively wrt phone A (rating 5/5), all other phones get a score of 1 or 2 out of 5. I would like it to be a little more fair, as it was just one phone with a very high value. Could you suggest me the best way to go about solving this issue where the relative grading is more fair? </p>

答: You might want to log(n) some of your scores. Then there will still be a relation between megapixels and score but not a linear one. (btw size of the sensor is a much better metric)</p>


问:
Why aren't there native Javascript interpreters for Windows/Mac/Linux?
It seems to me it would be very useful to use Javascript for general server side scripting tasks as it has more or less the same features as Perl and Python. But AFAIK there are no generally available Javascript interpreters for the major machine architectures. I guess the other problem may be lack of libraries but surely these would come if the interpreters were there. Google's V8 maybe could be a starting point. Does anyone think we'll see this soon?</p>

答:
Node.js is exactly what you're asking for ... and more.

In addition to being a JavaScript runtime it also provides APIs for common operations, such as file system access (JavaScript on the browser doesn't really need that) and network IO.

It's marketed for building network application (and it's great at that!), but it's really a general purpose JavaScript runtime that you can use to build anything you want. Also, it is based on V8.


答: This is called "grading on a curve", and reams of opinion have been written on the pros and cons of that idea. The question whether it is more "fair" to give scores that reflect the proportions of the values you measure, or to give scores that always contain a set number of high and low scores, is probably philosophically unanswerable. Whatever you do, make sure that the users actually know what your ratings mean. If a low rating only means "worst in the review", say so. If it means "approximately half as good as product Y", say so as well. (As others have pointed out, pixel counting is also a bad measure to estimate the quality of mobile cameras. But deciding what values to measure is a whole different issue, also very contentious.)

Title: Relative Scoring system - How to solve this?

Body:
I am trying to assign scores to phone's specifications to calculate a final rating score for each phone. </p>

<p>However, when I was scoring based on megapixels, I found that one of the phones 'A' has a 41MP camera. But all other phones have 8MP or less, which is pretty good for a phone. Right now, when I grade relatively wrt phone A (rating 5/5), all other phones get a score of 1 or 2 out of 5. I would like it to be a little more fair, as it was just one phone with a very high value. Could you suggest me the best way to go about solving this issue where the relative grading is more fair? </p>


问:
ReSharper's effect on coding interviews
Anyone who has used R# or CodeRush knows how fast you can put together simple constructs (and refactor complex ones) with a simple keyboard shortcut.  However, do these productivity plugins cause a false evaluation of ability during interviews?

Part of being a productive code writer (and making a good first impression in an interview) is writing good code - fast.

If I had two candidates:

Doesn't use plugins.  She thinks about the problem, sits down at a stock IDE at the interview PC that looks exactly like hers and types out the code in a minute or two, as usual.  Done.  Pass.

Uses plugins.  He thinks about the problem, sits down at a stock IDE at the interview PC and realizes "fe + tab" no longer writes a foreach loop automatically, and all the shortcuts are gone.  He then bumbles around the keyboard hitting his normal hotkeys and popping up strange windows and getting flustered.  It takes him 3 minutes to write what normally would take 30 seconds.  Done.  Looked like they didn't know their way around the IDE at times.  Must be new to this IDE and thus not had much experience with it or maybe the language.  Pass, but a 'meh' mark beside their name.

In your experience, how do you handle plugins during interviews as the interviewer or interviewee?  What are the best practices to getting what the candidate really knows?  There can be candidates who don't understand code, and use R# as a crutch.  There can also be candidates who know the code in and out and use R# because it's just plain faster than the built in VS or Eclipse templates.  Is it best to just not use an IDE at all?  Let them bring their own PC?  Others?

答:
Let them (candidates, that is) use whatever they want. The old, build a Wal-Mart with a Swiss army knife just to show you can approach is so old. They are going to use whatever it takes in their daily work (well, I certanly hope so) so let them use whatever they want in an interview. The final result is all that matters. And I'll much more gladly hire a candidate who knows what tools are available on the market, and how to use them efficiently, then the one who does it all manually. This is a killer industry.

p.s. As an example, think of Vim (or Emacs) - would you like to use it without any customized settings, plugins, etc.?

ContentLicense: CC BY-SA 2.5

Title: ReSharper's effect on coding interviews


问:
Does C# give you "less rope to hang yourself" than C++?
Joel Spolsky characterized C++ as "enough rope to hang yourself".  Actually, he was summarizing "Effective C++" by Scott Meyers:

It's a book that basically says, C++ is enough rope to hang yourself, and then a couple of extra miles of rope, and then a couple of suicide pills that are disguised as M&Ms...

I don't have a copy of the book, but there are indications that much of the book relates to pitfalls of managing memory which seem like would be rendered moot in C# because the runtime manages those issues for you.

Here are my questions:

Does C# avoid pitfalls that are avoided in C++ only by careful programming?  If so, to what degree and how are they avoided?

Are there new, different pitfalls in C# that a new C# programmer should be aware of?  If so, why couldn't they be avoided by the design of C#?

答:
Does C# avoid pitfalls that are avoided in C++ only by careful
  programming? If so, to what degree and how are they avoided?

C# has the advantages of:

Not being backwards-compatible with C, thus avoiding having a long list of "evil" language features (e.g., raw pointers) that are syntactically convenient but now considered bad style.

Having reference semantics instead of value semantics, which makes at least 10 of the Effective C++ items moot (but introduces new pitfalls).

Having less implementation-defined behavior than C++.

In particular, in C++ the character encoding of char, string, etc. is implementation-defined.  The schism between the Windows approach to Unicode (wchar_t for UTF-16, char for obsolete "code pages") and the *nix approach (UTF-8) causes great difficulties in cross-platform code.  C#, OTOH, guarantees that a string is UTF-16.

Are there new, different pitfalls in C# that a new C# programmer
  should be aware of?

Yes: IDisposable

Is there an equivalent book to "Effective C++" for C#?

There's a book called Effective C# which is similar in structure to Effective C++.


问:
How to unit test a function that is refactored to strategy pattern?
If I have a function in my code that goes like:

```<code>class Employee{

    public string calculateTax(string name, int salary)
    {
        switch (name)
        {
            case "Chris":
                doSomething($salary);
            case "David":
                doSomethingDifferent($salary);
            case "Scott":
               doOtherThing($salary);
       }
}
</code>```

Normally I would refactor this to use Ploymorphism using a factory class and strategy pattern:

```<code>public string calculateTax(string name)
{
    InameHandler nameHandler = NameHandlerFactory::getHandler(name);
    nameHandler->calculateTax($salary);
}
</code>```

Now if I were using TDD then I would have some tests that work on the original calculateTax() before refactoring.

ex:

```<code>calculateTax_givenChrisSalaryBelowThreshold_Expect111(){}
calculateTax_givenChrisSalaryAboveThreshold_Expect111(){}

calculateTax_givenDavidSalaryBelowThreshold_Expect222(){}
calculateTax_givenDavidSalaryAboveThreshold_Expect222(){}

calculateTax_givenScottSalaryBelowThreshold_Expect333(){}
calculateTax_givenScottSalaryAboveThreshold_Expect333(){}
</code>```

After refactoring I'll have a Factory class NameHandlerFactory and at least 3 implementation of InameHandler.

How should I proceed to refactor my tests? Should I delete the unit test for claculateTax() from EmployeeTests and create a Test class for each implementation of InameHandler?

Should I test the Factory class too?

答:
Before writing any code, I would start with a test for a Factory. Mocking the stuff I need I would force myself to think about the implementations and usecases.

Than I would implement a Factory and continue with a test for each implementation and finally the implementations themselves for those tests.

Finally I would remove the old tests.


答:
An alternative could be basing scores on the weighted average, instead of the highest value.

You assign for example 3.5 to the weighted average and then you calculate scores with a simple proportion:

score = value * 3.5 / weighted_mean

Scores above 5 (like the 41MP camera) will be cut down to 5, because it is the maximum allowed score.


问:
Is there any way to remove this redundancy?
I currently have the following HTML code

```<code>  <time datetime="2012-08-23">
    23. August 2012
  </time>
</code>```

I have that because I felt the "23. August 2012" format was easier for website visitors to read than

```<code><time>2012-08-23</time>
</code>```

Both of those HTML5 examples validate at w3, but the first one is obviously redundant, and I like to cut out markup I don't need.  Is there another date formate that I can use in the second example that is (1) easy for website visitors to read, and (2) w3 valid?

答:
You have two possibilities. First you can use the attribute "datetime" and the content as free text. On the other hand you have the option to use the content only. With the content only you need to fill in a valid format for the datetime. Currently it has the following format:

YYYY-MM-DDThh:mm:ssTZD

In time, no common browser is supporting this tag by default. I could think that there will maybe a time where the tag can handle current culture and different time formats as well. But in time it's not specified.

Therefore you only have the possibility to do it with that kind of redundancy, to stay HTML-conform. Sorry for that.


答:
Windows Script Host has included a JScript (javascript) engine since at least Windows 2000 out of the box, allowing you to do sysadmin tasks using javascript.

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

It's also possible to embed this into a windows application using the WScript.Shell ActiveX/COM object.

Title: Why aren't there native Javascript interpreters for Windows/Mac/Linux?

Body: It seems to me it would be very useful to use Javascript for general server side scripting tasks as it has more or less the same features as Perl and Python. But AFAIK there are no generally available Javascript interpreters for the major machine architectures. I guess the other problem may be lack of libraries but surely these would come if the interpreters were there. Google's V8 maybe could be a starting point. Does anyone think we'll see this soon?</p>


答:
As mentioned by Joachim, node.js is exactly what you ask for.

It appears to not be well known when compared with Python and especially Perl for this type of thing, but perhaps that is simply because JavaScript isn't widely considered to be very good.


答:
The old tests are just fine for verifying that calculateTax still works as it should. However, you don't need many test cases for this, only 3 (or maybe some more, if you want to test error handling too, using unexpected values of name).

Each of the individual cases (at the moment implemented in doSomething et al.) must have their own set of tests too, which test the inner details and special cases related to each implementation. In the new setup these tests could / should be converted into direct tests on the respective Strategy class.

I prefer to remove old unit tests only if the code they exercise, and the functionality it implements, completely ceases to exist. Otherwise, the knowledge encoded into these tests is still relevant, only the tests need to be refactored themselves.

Update

There may be some duplication between the tests of calculateTax (let's call them high level tests) and the tests for the individual calculation strategies (low level tests) - it depends on your implementation.

I guess the original implementation of your tests asserts the result of the specific tax calculation, implicitly verifying that the specific calculation strategy was used to produce it. If you keep this schema, you will have duplication indeed. However, as @Kristof hinted, you may implement the high level tests using mocks too, to verify only that the right kind of (mock) strategy was selected and invoked by calculateTax. In this case there will be no duplication between high and low level tests.

So if refactoring the affected tests isn't too costly, I would prefer the latter approach. However, in real life, when doing some massive refactoring, I do tolerate a small amount of test code duplication if it saves me enough time :-)

Should I test the Factory class too?

Again, it depends. Note that the tests of calculateTax effectively test the factory. So if the factory code is a trivial switch block like your code above, these tests may be all you need. But if the factory does some more tricky things, you may want to dedicate some tests specifically for it. It all boils down to how much tests you need to be confident that the code in question really works. If, upon reading the code - or analysing code coverage data - you see untested execution paths, dedicate some more tests to exercise these. Then repeat this until you are fully confident in your code.

Title: How to unit test a function that is refactored to strategy pattern?

Body:
If I have a function in my code that goes like:

```<code>class Employee{

    public string calculateTax(string name, int salary)
    {
        switch (name)
        {
            case "Chris":
                doSomething($salary);
            case "David":
                doSomethingDifferent($salary);
            case "Scott":
               doOtherThing($salary);
       }
}
</code>```

Normally I would refactor this to use Ploymorphism using a factory class and strategy pattern:

```<code>public string calculateTax(string name)
{
    InameHandler nameHandler = NameHandlerFactory::getHandler(name);
    nameHandler->calculateTax($salary);
}
</code>```

Now if I were using TDD then I would have some tests that work on the original calculateTax() before refactoring.

ex:

```<code>calculateTax_givenChrisSalaryBelowThreshold_Expect111(){}
calculateTax_givenChrisSalaryAboveThreshold_Expect111(){}

calculateTax_givenDavidSalaryBelowThreshold_Expect222(){}
calculateTax_givenDavidSalaryAboveThreshold_Expect222(){}

calculateTax_givenScottSalaryBelowThreshold_Expect333(){}
calculateTax_givenScottSalaryAboveThreshold_Expect333(){}
</code>```

After refactoring I'll have a Factory class NameHandlerFactory and at least 3 implementation of InameHandler.

How should I proceed to refactor my tests? Should I delete the unit test for claculateTax() from EmployeeTests and create a Test class for each implementation of InameHandler?

Should I test the Factory class too?


答:
I'll start by saying that I'm no expert on TDD or unit testing, but here's how I would test this (I'll use pseudo-like code):

```<code>CalculateTaxDelegatesToNameHandler()
{
    INameHandlerFactory fakeNameHandlerFactory = Fake(INameHandlerFactory);
    INameHandler fakeNameHandler = Fake(INameHandler);

    A.Call.To(fakeNameHandlerFactory.getHandler("John")).Returns(fakeNameHandler);

    Employee employee = new Employee(fakeNameHandlerFactory);
    employee.CalculateTax("John");

    Assert.That.WasCalled(fakeNameHandler.calculateTax());
}
</code>```

So I'd test that the calculateTax() method of employee class correctly asks its NameHandlerFactory for a NameHandler and then calls the calculateTax() method of the returned NameHandler.

Body:
I'll start by saying that I'm no expert on TDD or unit testing, but here's how I would test this (I'll use pseudo-like code):

CalculateTaxDelegatesToNameHandler()
{
    INameHandlerFactory fakeNameHandlerFactory = Fake(INameHandlerFactory);
    INameHandler fakeNameHandler = Fake(INameHandler);

    A.Call.To(fakeNameHandlerFactory.getHandler("John")).Returns(fakeNameHandler);

    Employee employee = new Employee(fakeNameHandlerFactory);
    employee.CalculateTax("John");

    Assert.That.WasCalled(fakeNameHandler.calculateTax());
}

So I'd test that the calculateTax() method of employee class correctly asks its NameHandlerFactory for a NameHandler and then calls the calculateTax() method of the returned NameHandler.


问:
TDD with SQL and data manipulation functions
While I'm a professional programmer, I've never been formally trained in software engineering. As I'm frequently visiting here and SO, I've noticed a trend for writing unit tests whenever possible and, as my software gets more complex and sophisticated, I see automated testing as a good idea in aiding debugging.

However, most of my work involves writing complex SQL and then processing the output in some way. How would you write a test to ensure your SQL was returning the correct data, for example? Then, say if the data wasn't under your control (e.g., that of a 3rd party system), how can you efficiently test your processing routines without having to hand write reams of dummy data?

The best solution I can think of is making views of the data that, together, cover most cases. I can then join those views with my SQL to see if it's returning the correct records and manually process the views to see if my functions, etc. are doing what they're supposed to. Still, it seems excessive and flakey; particularly finding data to test against...

答:
If your database platform is SQL Server, there is a very nice free tool: tSQLt.

tSQLt is a database unit testing framework for Microsoft SQL Server. tSQLt is compatible with SQL Server 2005 (service pack 2 required) and above on all editions.

I have successfully used to implement testing at the database level.

Some of the key elements that make it so useful include:

Ability to work with fake tables and views which reduces the setup normal involved

Tests automatically run in transactions (so easily re-runable)

Your asserts can do comparisons on tables (both real and fake) so you can see if you have changed any data easily


问:
Why is Java the lingua franca at so many institutions?
EDIT: This question at first seems to be bashing Java, and I guess at this point it is a bit. However, the bigger point I am trying to make is why any one single language is chosen as the one end all be all solution to all problems. Java happens to be the one that's used so that's the one I had to beat on here, but I'm not intentionality ripping Java a new one :)

I don't like Java in most academic settings. I'm not saying the language itself is bad -- it has several extremely desirable aspects, most importantly the ability to run without recompilation on most any platform. Nothing wrong with using the language for Your Next App ^TM. (Not something I would personally do, but that's more because I have less experience with it, rather than it's design being poor)

I think it is a waste that high level CS courses are taught using Java as a language. Too many of my co-students cannot program worth a damn, because they don't know how to work in a non-garbage-collected world. They don't fundamentally understand the machines they are programming for. When someone can work outside of a garbage collected world, they can work inside of one, but not vice versa. GC is a tool, not a crutch. But the way it is used to teach computer science students is a as a crutch.

Computer science should not teach an entire suite of courses tailored to a single language. Students leave with the idea that all good design is idiomatic Java design, and that Object Oriented Design is the ONE TRUE WAY THAT IS THE ONLY WAY THINGS CAN BE DONE. Other languages, at least one of them not being a garbage collected language, should be used in teaching, in order to give the graduate a better understanding of the machines.

It is an embarrassment that somebody with a PHD in CS from a respected institution cannot program their way out of a paper bag.

What's worse, is that when I talk to those CS professors who actually do understand how things operate, they share feelings like this, that we're doing a disservice to our students by doing everything in Java. (Note that the above would be the same if I replaced it with any other language, generally using a single language is the problem, not Java itself)

In total, I feel I can no longer respect any kind of degree at all -- when I can't see those around me able to program their way out of fizzbuzz problems.

Why/how did it get to be this way?

答: Is it too much to ask that they be taught something about how computers really work? It makes no sense to me that any CS course outline would not include something of operating systems and computer archetecture. I'm not saying you should be able to design a computer on the back of an envelope, but a general overview puts all languages into perpective. I mean, Java runs in a virtual machine!


问:
Should I use both WCF and ASP.NET Web API
We already have a WCF API with basichttpbinding.
Some of the calls have complex objects in both the response and request.

We need to add RESTful abilities to the API.
at first I tried adding a webHttp endpoint, but I got

```<code>At most one body parameter can be serialized without wrapper elements
</code>```

If I made it Wrapped it wasn't pure as I need it to be.

I got to read this, and this (which states "ASP.NET Web API is the new way to build RESTful service on .NET").

So my question is, should I make 2 APIs(2 different projects)? one for SOAP with WCF and one RESTful with ASP.NET Web API? is there anything wrong architecturally speaking with this approach?

答:
The new Web API included in the new ASP.NET MVC is good for adding restful services to pages to enable some AJAX functionalities. It is good if you only want to have a small API or something like that but rest only.

In the moment where you implement REST and SOAP as a bigger API I would allways prefer to use a WCF application. I think this approach is better to maintain and you have all web services located in a central project.


问:
Returning an IQueryable from an IRepository
Using the Repository pattern, is it proper to return an IQueryable of a data set (table), for generic usage?

It is very handy in many cases, especially when using external libraries that leverage that interface, for example some plugins that sort/filter and bind to ui elements.

However, exposing an IQueryable sometimes seems to leave the design prone to errors. This, coupled with a wrong usage of lazy loading could lead to severe performance hits.

On the other hand, having access methods for every single usage seems redundant and also a lot of work (considering unit tests etc).

答:
There will be no consensus on this one. In my opinion and experience, a Repository should return objects with specific uses. At leas if you use Repository Pattern as defined by Eric Evens in DDD. A Repository is a "bridge" connecting business logic, persistence and factories.

If you would like access to persistence more directly, maybe you are looking for the Gateway Pattern.

However, from what you say here, you would like to hide that exposure to persistence so the Proxy Pattern may com in handy for you.


答:
Mark Seemann has an excellent blog post about this subject: IQueryable is Tight Coupling. He sums it up nicely in the final part (emphasis mine):

You may think this is all a theoretical exercise, but it actually does matter. When writing Clean Code, it's important to design an API in such a way that it's clear what it does.

An interface like this makes false guarantees:

```<code>public interface IRepository
{
    IQueryable<T> Query<T>();
}
</code>```

According to the LSP and Postel's law, it would seem to guarantee that you can write any query expression (no matter how complex) against the returned instance, and it would always work.

In practice, this is never going to happen.

Programmers who define such interfaces invariably have a specific ORM in mind, and they implicitly tend to stay within the bounds they know are safe for that specific ORM. This is a leaky abstraction.

If you have a specific ORM in mind, then be explicit about it. Don't hide it behind an interface. It creates the illusion that you can replace one implementation with another. In practice, that's impossible. Imagine attempting to provide an implementation over an Event Store.

The cake is a lie.

ORM's like Entity Framework are implementations of the Repository and the Unit of Work pattern. There's no need to wrap them in another one.

Title: Returning an IQueryable from an IRepository

Body:
Using the Repository pattern, is it proper to return an IQueryable of a data set (table), for generic usage?

It is very handy in many cases, especially when using external libraries that leverage that interface, for example some plugins that sort/filter and bind to ui elements.

However, exposing an IQueryable sometimes seems to leave the design prone to errors. This, coupled with a wrong usage of lazy loading could lead to severe performance hits.

On the other hand, having access methods for every single usage seems redundant and also a lot of work (considering unit tests etc).

Body:
Mark Seemann has an excellent blog post about this subject: IQueryable is Tight Coupling. He sums it up nicely in the final part (emphasis mine):

You may think this is all a theoretical exercise, but it actually does matter. When writing Clean Code, it's important to design an API in such a way that it's clear what it does.

An interface like this makes false guarantees:

public interface IRepository
{
    IQueryable<T> Query<T>();
}

According to the LSP and Postel's law, it would seem to guarantee that you can write any query expression (no matter how complex) against the returned instance, and it would always work.

In practice, this is never going to happen.

Programmers who define such interfaces invariably have a specific ORM in mind, and they implicitly tend to stay within the bounds they know are safe for that specific ORM. This is a leaky abstraction.

If you have a specific ORM in mind, then be explicit about it. Don't hide it behind an interface. It creates the illusion that you can replace one implementation with another. In practice, that's impossible. Imagine attempting to provide an implementation over an Event Store.

The cake is a lie.

ORM's like Entity Framework are implementations of the Repository and the Unit of Work pattern. There's no need to wrap them in another one.