问:
What Are Some Tips For Writing A Large Number of Unit Tests?
I've recently been tasked with testing some COM objects of the desktop app I work on. What this means in practice is writing a large number (>100) unit tests to test different but related methods and objects. While the unit tests themselves are fairly straight forward (usually one or two Assert()-type checks per test), I'm struggling to figure out the best way to write these tests in a coherent, organized manner. What I have found is that copy and Paste coding should be avoided. It creates more problems than it's worth, and it's even worse than copy-and-paste code in production code because test code has to be more frequently updated and modified.

I'm leaning toward trying an OO-approach using but again, the sheer number makes even this approach daunting from an organizational standpoint due to concern with maintenance. It also doesn't help that the tests are currently written in C++, which adds some complexity with memory management issues.

Any thoughts or suggestions?

答: Don't forget that Cyclomatic Complexity of your tests must be the lowest (about 2). That will help you to avoid making bugs in unit-test. Tests must be as easy as you can do. So, don't try to make the best design and use all design patterns you know.</p>


答:
I'd like to offer the opposite opinion from Anton.

Unit tests are code. The fact that they are not shipped to the customer detracts in no way from their importance to your code base. They are an investment of your programming time that repays itself in the improved speed and accuracy of further modifications of the code base; therefore they merit any good design principle that would apply to your business code.

You give some hints about how duplication in the individual tests could be avoided; I say go for it. The improved understandability of a large test suite more than makes up for the effort of deduplication. Complexity of code, cyclomatic or otherwise, is of course a pressure that you should avoid as far as it's reasonable, but never let fear of abstraction prevent you from writing your tests as professionally as your application logic.

ContentLicense: CC BY-SA 3.0

Title: What Are Some Tips For Writing A Large Number of Unit Tests?

Body:
I've recently been tasked with testing some COM objects of the desktop app I work on. What this means in practice is writing a large number (>100) unit tests to test different but related methods and objects. While the unit tests themselves are fairly straight forward (usually one or two Assert()-type checks per test), I'm struggling to figure out the best way to write these tests in a coherent, organized manner. What I have found is that copy and Paste coding should be avoided. It creates more problems than it's worth, and it's even worse than copy-and-paste code in production code because test code has to be more frequently updated and modified.

I'm leaning toward trying an OO-approach using but again, the sheer number makes even this approach daunting from an organizational standpoint due to concern with maintenance. It also doesn't help that the tests are currently written in C++, which adds some complexity with memory management issues.

Any thoughts or suggestions?


答:
Any thoughts or suggestions?

Focus on one test at a time. Be consistent from one test to the next. Reevaluate your approach once you have ~10 tests under your belt.

Realistically, 100 unit tests at ~6-10 lines of code a piece is like a week's worth of work. Annoying, tedious work... but not a lot of it. Put your head down and don't over-think things.


问:
Migrating from jdbc to MyBatis -- advice needed
I am working on a Java application (an ERP) that has grown pretty large, and will continue to grow for the next couple of years. We have been using Spring-JDBC for our DAO layer. But the amount of boilerplate code that needs to be written is slowing us down significantly, not to mention introducing silly bugs in the system.

So now we're looking for a solution that will:

Reduce the amount of time we need to spend on the DAO layer

Doesn't have a very steep learning curve

Gives us control over our queries, like we have with JDBC.

We should be able port our existing code part-by-part, not all at once.

I thought MyBatis would be a good choice, but I'm not sure if it would satisfy all our requirements. In particular, would it be able to work alongside our Spring-JDBC code without creating problems in transaction management, handling concurrency etc?

Edit: Forgot to mention that we're using Spring-AOP for transaction management, which we'd prefer to continue with.

Thanks!

答:
Our apps use Spring and iBatis everything.  (well 99% of everything else, we still have some jdbc code that hasn't been ported yet).  We are also using Spring AOP for txn managment.

In short, MyBatis+Spring AOP will work for you.  It also works well with DBUnit for DAO integration testing.


问:
How to manage/organise when you have to multi-task on multiple 1 man projects?
We are a team of developers working on multiple small projects - a developer could have 3 or more 1 man projects to work on and keep moving. It can feel like your time is pretty fragmented & interrupted moving between project to project. Sometimes frustrating, stressful & overwhelming. In an ideal world it wouldn't be this way but it appears to be very common. When you are in a setup where it can't be avoided, how do you make the best of it?

I'm looking for ideas/tips/methods that will help increase productivity & reduce stress specifically in multi-tasking environments. DOs and DON'Ts etc. What boundaries, limits should be in place? Which development methodologies will & won't work? What do you know that does WORK?

Is there any good way to organise this kind of environment to be maximum productive?

答:
There's a number of factors to consider like due dates for projects, visibility to management, impact on the business, etc.

Generally though, I worked effectively with some rules I used:

Break it down by feature/bug we'll call them tasks. This implies that you're using some kind of task tracking mechanism, which you must due to the hopping from project-to-project. You need to know where you were and where you were going as soon as you get onto the project in order to minimize the context-switch overhead as much as possible.

Obviously, work through your tasks in priority order per-project.

Work a task to completion. Even if a priority 1 task for project A would normally take you longer than you allocate per-project, do it anyway. You'll have to re-figure out what you were trying to do when you get back to the project if you leave early.

If you have tasks given to you by management, create a priority queue, and make it available. If it's just a whiteboard, tell management that all tasks you're given go to the bottom of the pile. If they want it at the top, they have to see the tasks that they're pre-empting/interrupting.

Allocate a general amount of time per-project. If it's a day, a half-day, a week, whatever makes sense for your environment and try to stick to it (with the exception of finishing tasks as mentioned above). If you can fit 2 tasks in a morning for Project A, then do that. Don't split the projects up too much. As previously, if you're given a task for Project B and you're on Project A now, you can say something like: "Great, I'm on Project B tomorrow morning, and I'll take a look at it first thing in the morning."

Even if you do the same project back-to-back, keep it in your head that you have 2 work-sessions (periods of time to work on a project) that you're allocating for 1 project.

Split sessions up using effective separators: end-of-day, lunch, coffee break. Anything where your mind stops working 100%. The context-switch will be natural and you'd have to do it anyway even if you didn't switch projects.

The goal is to have a clearly defined schedule to manage wacky amounts of work/projects. If you stick to the schedule like:

```<code>        Mon Tues Wed Thurs Fri
Morn    A   B    A   B     A
Aft     A   C    C   C     C
</code>```

... then your metrics will be more accurate and predictable. If you are using burn-down charts for development/delivery dates, they'll be more accurate and predictable. It might take time creating a schedule that takes into account availability of certain managers, QA, other devs, software/hardware resources, whatever, but once you've got one down, it'll be business as usual and you won't get so flustered.

Body:
There's a number of factors to consider like due dates for projects, visibility to management, impact on the business, etc.

Generally though, I worked effectively with some rules I used:

Break it down by feature/bug we'll call them tasks. This implies that you're using some kind of task tracking mechanism, which you must due to the hopping from project-to-project. You need to know where you were and where you were going as soon as you get onto the project in order to minimize the context-switch overhead as much as possible.

Obviously, work through your tasks in priority order per-project.

Work a task to completion. Even if a priority 1 task for project A would normally take you longer than you allocate per-project, do it anyway. You'll have to re-figure out what you were trying to do when you get back to the project if you leave early.

If you have tasks given to you by management, create a priority queue, and make it available. If it's just a whiteboard, tell management that all tasks you're given go to the bottom of the pile. If they want it at the top, they have to see the tasks that they're pre-empting/interrupting.

Allocate a general amount of time per-project. If it's a day, a half-day, a week, whatever makes sense for your environment and try to stick to it (with the exception of finishing tasks as mentioned above). If you can fit 2 tasks in a morning for Project A, then do that. Don't split the projects up too much. As previously, if you're given a task for Project B and you're on Project A now, you can say something like: "Great, I'm on Project B tomorrow morning, and I'll take a look at it first thing in the morning."

Even if you do the same project back-to-back, keep it in your head that you have 2 work-sessions (periods of time to work on a project) that you're allocating for 1 project.

Split sessions up using effective separators: end-of-day, lunch, coffee break. Anything where your mind stops working 100%. The context-switch will be natural and you'd have to do it anyway even if you didn't switch projects.

The goal is to have a clearly defined schedule to manage wacky amounts of work/projects. If you stick to the schedule like:

        Mon Tues Wed Thurs Fri
Morn    A   B    A   B     A
Aft     A   C    C   C     C

... then your metrics will be more accurate and predictable. If you are using burn-down charts for development/delivery dates, they'll be more accurate and predictable. It might take time creating a schedule that takes into account availability of certain managers, QA, other devs, software/hardware resources, whatever, but once you've got one down, it'll be business as usual and you won't get so flustered.


问:
Naming a "do X if needed" method
What is a good way to name a method that checks if X needs to be done, and does X it if necessary?

For example, how to name a method that updates a user list if new users have logged in? UpdateListIfNeeded seems too long, while simple UpdateList implies a possibly expensive and unnecessary operation is done every time. EnsureListUpdated is a variant as well.

C# has a bool TryXXX(args, out result) pattern (e.g. int.TryParse(str, out num)) to check if X is possible and do it, but that is subtly different.

答:
My preference is UpdateList.  If nothing needs to be done, so be it.  The expense should always be minimized anyway, so if UpdateList is doing more than necessary something is incorrect in its implementation.

Basically it's the verb that tells you what the method should do.  CalculateX should always recalculate X.  GetY should always return Y, but only do the work of retrieving it if necessary.  Likewise, UpdateZ requests an update of Z assuming it's done the most efficient way possible.

Title: Naming a "do X if needed" method


答: I tend to use Ensure.  It carries the meaning of making sure that something is taken care of, however that needs to be done.  If it's already fine, just check it and we're done.  Otherwise, do it.  Either way, just ensure that it gets done.

Title: Naming a "do X if needed" method

Body:
What is a good way to name a method that checks if X needs to be done, and does X it if necessary?

For example, how to name a method that updates a user list if new users have logged in? UpdateListIfNeeded seems too long, while simple UpdateList implies a possibly expensive and unnecessary operation is done every time. EnsureListUpdated is a variant as well.

C# has a bool TryXXX(args, out result) pattern (e.g. int.TryParse(str, out num)) to check if X is possible and do it, but that is subtly different.


答:
Call me "Maybe"

Co-opted from Haskell snippets I've seen, try

```<code>UpdateListMaybe();
</code>```

Title: Naming a "do X if needed" method

Body:
Call me "Maybe"

Co-opted from Haskell snippets I've seen, try

UpdateListMaybe();


答:
What SnOrfus suggests will work well with smaller, well defined projects if you are disciplined.  With larger, more exploratory projects, programmer multitasking is largely a management myth.  Joel Spolsky says never let people work on more than one thing at once.  The more often you switch projects, the less you accomplish.

I had a boss who insisted that I "multitask."  My strategy was always to prioritize across projects and do the highest priority thing first, sticking with a single project for as long as possible.  Sometimes I would hold off reporting progress on one thing so that I could stagger my progress reports to make it look like I was switching back and forth.  Then I would lie and say "Yes" I was multitasking.  Sometimes you can do all the really quick projects first so you can concentrate on a longer one (and report a shorter one done each day while you concentrate on the longer one).  I was always very productive this way and my boss was very happy (if a little misinformed).  For the record, I tried reasoning with him first, and only lied when that failed.

One exception to this rule is interruptions to handle tech support requests.  Nothing is more important to a programmer than an intimate understanding of the needs of the customer.  The benefit of that understanding is worth the cost of breaking concentration (within reason).

Good luck!

Title: How to manage/organise when you have to multi-task on multiple 1 man projects?

Body:
We are a team of developers working on multiple small projects - a developer could have 3 or more 1 man projects to work on and keep moving. It can feel like your time is pretty fragmented & interrupted moving between project to project. Sometimes frustrating, stressful & overwhelming. In an ideal world it wouldn't be this way but it appears to be very common. When you are in a setup where it can't be avoided, how do you make the best of it?

I'm looking for ideas/tips/methods that will help increase productivity & reduce stress specifically in multi-tasking environments. DOs and DON'Ts etc. What boundaries, limits should be in place? Which development methodologies will & won't work? What do you know that does WORK?

Is there any good way to organise this kind of environment to be maximum productive?


问:
What does “S” stands for in OOPS?
I have searched for the full form of "OOPS" in Google, but unfortunately, there are many ambiguous answers. Some say it's "Systems", and some say it's "Structure", and some have even mentioned it as "Synopsis".

Can anybody please enlighten me, to find the full form of OOPS, with some proper & correct reference?

Many thanks to everyone, helping me out.

答:
Everywhere I look, the people that use "OOPS" are not people whose native language is English. I truly believe therefore that many developers use "OOPS" out of habit; it is done because other developers do.

I think it is important to make it clear that the term is Object Oriented Programming and the "S" is extraneous. If you search the internet for "object oriented programming system" then you will get some results but not many results.

Object Oriented Programming is a philosophy; it is improper to call it a system. A system would be something that implements the Object Oriented Programming philosophy.

Title: What does “S” stands for in OOPS?


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
I disagree with dsimcha's answer for the most part:

Teaching OO from the beginning is not really a bad idea within itself, neither is teaching procedural languages. What's important is that we teach people to write clear, concise, cohesive code, regardless of OO or procedural.

Individual methods in good OO programs DO NOT tend to be procedural looking at all.  This is becoming more and more true with evolution of OO languages (read C# because other than C++ that's the only other OO language I know) and their syntax that's getting more complex by the day (lambdas, LINQ to objects, etc.).  The only similarity between OO methods and procedures in procedural languages is the linear nature of each, which I doubt  would change anytime soon.

You can't master a procedural language without understanding data structures either.  The pointer concept is as important for procedural languages as for OO languages.  Passing parameters by reference, for example, which is quite common in procedural languages, requires you to understand pointers as much as it's required to learn any OO language.

I don't think that design patterns should be taught early in OO programming at all, because they are not fundamental to OO programming at all.  One can definitely be a good OO programmer without knowing anything about design patterns.  In fact a person can even be using well-known design patterns without even knowing that they are documented as such with proper names and that books are written about them.  What should be taught fundamentally is design principles such as Single Responsibility, Open Close, and Interface Segregation.  Unfortunately, many people who consider themselves OO programmers these days are either not familiar with this fundamental concept or just choose to ignore it and that's why we have so much garbage OO code out there.  Only after a thorough understanding of these and other principles should design patterns be introduced.

To answer original poster's question, yes, OO is a harder concept to understand than procedural programming.  This is because we do not think in terms of properties and methods of real life objects.  For example, human brain does not readily think of "TurnOn" as a method of TV, but sees it as a function of human turning on the TV.  Similarly, polymorphism is a foreign concept to a human brain that generally sees each real life object by only one "face".  Inheritance again is not natural to our brains.  Just because I am a developer does not mean that my son would be one.  Generally speaking, human brain needs to be trained to learn OO while procedural languages are more natural to it.

ContentLicense: CC BY-SA 2.5

Title: Why is OOP difficult?


问:
Can I use code in my own projects that I have written for someone else?
In the past I did a freelancing project for someone where I wrote a couple of image filters. Nothing fancy, and a very very low cost project for them. I was wondering, if I wish to use these in a project of mine, would I legally/ethically be allowed to do that? If I couldn't use the exact code, could I at least use the general data I used to make them. (I modeled the filters in Photoshop and then coded a duplicate filter in a programming language.)

My specific work was done through freelancer.com and we had no special terms or conditions.

答:
In general, if there was no particular term regarding code ownership and copyright, then the copyright is yours.

In some countries, the ownership may be considered to be the company the work was done for (work for tender).

Of course this entirely depends on jurisdiction and you should consult a local lawyer to get an answer that will suite your particular situation and location.


问:
What is the difference (if any) between (null != $object) and ($object != null) when using PHP?
I am used to Java and therefore always think conditions are interpreted from left to right, i.e. there is a vital difference in null != $obj and $obj != null

Now this seems not to be the case with PHP.

Can I do something wrong in PHP when I always start with null on the left-hand side? Can I keep my behaviour from Java or do I need to train myself to do something else when dealing with PHP conditions?

答:
There is no (technical) difference – nor is there in Java to my knowledge.

In PHP, do not use either of these.

I recommend you always use the strict comparison operators === and !== if possible. You will know when you actually need loose comparison operators.

Misunderstandings

I believe you may be confused about a couple of things:

short-circuiting operators

order of evaluation

operator precedence

I just found that the PHP manual says:
  "PHP checks each condition in order from left to right"

No,

the PHP manual does not say that, it's a comment.

PHP does not do that.

PHP evaluates the conditions from left to right, but it stops once the result is known:

expr1 && expr2
```

If expr1 evaluates to false, expr2 will not be evaluated. This is called short-circuiting and it does not seem to be very well-documented – I couldn't find any other official note on the matter except for the comment in Example #1. It is a well-known feature, though.

Fallacies

I am used to Java and therefore always think conditions are interpreted from left to right, i.e. there is a vital difference in null != $obj and $obj != null

PHP checks each condition in order from left to right

  Ergo: The same "best practice" can be applied

Ergo: nothing – non sequitur. The conclusion does not follow from the premise. Using constant == $variable or $variable == constant is not connected to either of short-circuiting, order of evaluation or operator precedence.

Undefined behavior

Both operands of != are always evaluated. In the case of PHP, the evaluation order (which is irrelevant here) is actually unspecified (as in absent from the documentation).

Body:
There is no (technical) difference – nor is there in Java to my knowledge.

In PHP, do not use either of these.

I recommend you always use the strict comparison operators === and !== if possible. You will know when you actually need loose comparison operators.

Misunderstandings

I believe you may be confused about a couple of things:

short-circuiting operators

order of evaluation

operator precedence

I just found that the PHP manual says:
  "PHP checks each condition in order from left to right"

No,

the PHP manual does not say that, it's a comment.

PHP does not do that.

PHP evaluates the conditions from left to right, but it stops once the result is known:

expr1 && expr2

If expr1 evaluates to false, expr2 will not be evaluated. This is called short-circuiting and it does not seem to be very well-documented – I couldn't find any other official note on the matter except for the comment in Example #1. It is a well-known feature, though.

Fallacies

I am used to Java and therefore always think conditions are interpreted from left to right, i.e. there is a vital difference in null != $obj and $obj != null

PHP checks each condition in order from left to right

  Ergo: The same "best practice" can be applied

Ergo: nothing – non sequitur. The conclusion does not follow from the premise. Using constant == $variable or $variable == constant is not connected to either of short-circuiting, order of evaluation or operator precedence.

Undefined behavior

Both operands of != are always evaluated. In the case of PHP, the evaluation order (which is irrelevant here) is actually unspecified (as in absent from the documentation).


问:
Confused on selling GPL. How is it consistent with this section?
(Written against GPLv2.)

It is always said that GPL does not prohibit selling the software, as long as its source code is provided under the same license (GPL). Now, I do not understand how it is consistent with Section 2b:

You must cause any work that you distribute or publish, that in
      whole or in part contains or is derived from the Program or any
      part thereof, to be licensed as a whole at no charge to all third
      parties under the terms of this License.

I don't get it. Does not this clause prohibit selling the software? If not, then what exactly does it trying to say?

EDIT: Following the answers below, I wish to note that answering a question "everyone says that GPL says A but this part of GPL says B, how is it?" with "everyone says A so GPL must mean A" is not an answer.

答:
Disclaimer: I'm not a lawyer

(section 2a)

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.

This indeed confirms that you may charge a fee in some cases. e.g. warranty protection.
Since "you" refers to any licensee, this means anyone who licenses the program may do so. Any licensee who wishes to become a "warranty seller" can.

(section 2b, emphasis added)

You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.

This means that every licensee must not charge to license the program. However, you may still charge for warranties, etc. Provided you also offer a version of the program without that warranty.
As for the physical transfer fee, that might be an issue. However, since the licensee can freely distribute it, only one person would be required to pay that fee - then that person could redistribute it to others for free.

This section might be problematic:

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.

If I understand this correctly, that means that artwork etc. may not be GPLed, but when distributed as a whole, then it must be GPLed.

This means that a game that's distributed "as a whole" must include the artwork as GPL.

If you can't license the artwork as GPL, then the GPLed portions of the game can't be distributed as a whole either. For this situation, dual-licensing seems to be the only option.

My understanding of what a "whole" is is kind of fuzzy, though.


问:
SQL Server Management Studio Show last executed query
I am looking for a way for SQL Server Management studio to show me the last SQL query that was run. For example, when I make modifications to a table in the designer mode, I will eventually want to make the same changes to the production DB without recreating the entire table. I'm looking for functionality similar to PHPMyAdmin for MySQL which tells you the last query ran and the results of the query at the top of the page after the modifications are complete.</p>

答:
If you want to know what is the query corresponding to the change you've done to a table (or other object) in designer mode, use Generate Change Script (Table Designer → Generate Change Script... or the very first icon, with a diskette and a script, in Table Designer toolbar) command.

Note that actually you don't need to commit the changes, which makes it a good medium to learn things. For example, if you've forgotten how to create a primary key which spans on multiple columns, one way is to Google it; another one is to create such key and see the change script.

If you rather want to track all the queries, not just the ones made by the designer, use the profiler (Tools → Sql Server Profiler).


问:
Writing a CSS parser in C#. What do you think is the best strategy?
I'm in the middle of writing a CSS parser in C#. I'm well under way, but I also have those times where I wonder if I'm taking the best approach. The things I've considered are:

Feed the CSS grammar from the W3C into a parser generator and working off that.

Hand-code a CSS parser off the grammar.

Use a generated tokenizer, but hand-code the parsing of the productions.

The reverse of (3) - generate the productions, but hand-code the tokenizer.

Without revealing my current approach, I was wondering how others feel about this, and appreciate any comments and guidance from your experience. Part of this is also to see what questions people ask and compare the questions to what I asked myself.

答:
I converted the published CSS grammar to a syntax that can be handled by the GOLD Parser.

My reasoning was that that my using a machine-generated parser derived from the formal grammar was the most likely way to get an accurate and maintainable solution.

I am happy with the result.

The main defect (that I want to work on next) is the error-recovery (as mentioned by Dean Harding in his answer): my current implementation can only parse correct CSS.


答:
EDIT in response to comment. I Am Not A Lawyer. If you want a legal explanation about what each section in the GPL means, and how they interact, contact a lawyer in your jurisdiction. The answer below explains the overall meaning of the GPL as explained in the FAQ. My understanding is that this is correct in many jurisdictions (i.e. it has been tested in court).

Technically the GPL does not prohibit selling software. But it does require that any purchaser must be allowed to distribute the software to anyone else, free.

Clearly this requirement effectively prohibits many business models for selling software for a living! You may be able to make some money by selling other things along with the software: support, warranties, training, documentation, consultancy, hardware...

If you own the copyright on the software, you can dual-license it: sell a paid version under different license terms.

Title: Confused on selling GPL. How is it consistent with this section?

Body:
(Written against GPLv2.)

It is always said that GPL does not prohibit selling the software, as long as its source code is provided under the same license (GPL). Now, I do not understand how it is consistent with Section 2b:

You must cause any work that you distribute or publish, that in
      whole or in part contains or is derived from the Program or any
      part thereof, to be licensed as a whole at no charge to all third
      parties under the terms of this License.

I don't get it. Does not this clause prohibit selling the software? If not, then what exactly does it trying to say?

EDIT: Following the answers below, I wish to note that answering a question "everyone says that GPL says A but this part of GPL says B, how is it?" with "everyone says A so GPL must mean A" is not an answer.


答:
I'd done GW-Basic and Turbo Pascal programming a fair bit before being introduced to OO, so initially it DID do my head in.

No idea if this is what happens to others, but to me it was like this: my thought process about programming was purely procedural. As in: "such and such happens, then such and such happens next", etc. I never considered the variables and data to be anything more than fleeting actors in the flow of the program. Programming was "the flow of actions".

I suppose what wasn't easy to grasp (as stupid as that looks to me now), was the idea that the data/variables actually truly matter, in a deeper sense than just being fleeting actors in program "flow". Or to put this another way: I kept trying to understand it via what happens, rather than via what is, which is the real key to grasping it.

Title: Why is OOP difficult?

Body:
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?


问:
What is the best way to divide work among developers
My team and I are rebuilding a site we developed around ten years ago, and we want to do it in Agile.

So after I spent a lot of time reading (probably not enough) I am having trouble with the question how to divide work between developers.

I'll be more specific and say that the site is divided to separate modules that doesn't have much integration between one another.

What is the best / Most accepted way to divide the work between the developers?

Giving each person a different module to work on.

Assign all developers to the same module, and split the work by different parts of the module (UnitTesting, DAL and Mapping, Logics, UI)

Assign all developers to the same module, and split the work by different logics (For example each developer is in-charge of a specific logic(probably a method in the BL) and It's UnitTesting, DAL and Mapping and UI...

Or maybe something entirely different?

答:
No developer team organizational discussion would be complete without mentioning Dr. Fred Brooks' Surgical Team.

The basic formula is: one Surgical Team per Unit of Work

Defining a Surgical Team

The concept of the surgical team is based on two fundamental ideas:

Fewer developers are better per unit of work because cross-talk kills productivity.

High-output developers way out-perform low-output developers (and according to Brooks, there is no such thing as a medium-output developer), so you had better give them the most important work to do, and limit their distractions.

A surgical team is comprised of 3-10 developers:

A chief programmer. A high-output developer, who does most of the actual programming.

A co-pilot. Another high-output developer, who does some programming, but also some administrative tasks, like attending meetings and gathering requirements.

1 - 8 assistants.  Brooks describes these as developers responsible for things like documentation, code cleanup, research, writing tools/algorithms, testing, etc.  Back in the 60s Brooks proposed exactly 8 roles, but with modern tools you may need as little as 1 or 2, and should probably be assigned based on your project's needs.

Defining a Unit of Work

So now that we can put together a team, what do we assign them?

If the project is very small, this is easy.  You assign one surgical team to the whole project.

Otherwise, then you will need start with a person or team that is in charge of the entire project's architecture.  It will be their job to modularize the software appropriately so that work can be split amongst additional sub-teams.  The achitecture team can also take on other work, too, as to not spread developers too thin.

You should see three basic, acceptable patterns emerge:

Exactly 1 sub-team for each layer (UI, DAL, etc)

Exactly 1 sub-team for each module (Home Page, Support Site, Shop)

A mix of the two (a low-level framework team, and a UI-focused team for each module)

OwnerDisplayName: Amir


答:
I am not a lawyer either, but here's how I see it:

A sales agreement is a contract between you (the first party) and the buyer (the second party).  The clause you have quoted says absolutely nothing about anything that happens between the first party and the second party.

What the clause does say is, the program itself must be available free of charge to all third parties, i.e. anyone who has not entered into a sales agreement with you.  So, if the program is the only thing you're actually selling, there is no incentive whatsoever for me to enter into a sales agreement with you and pay money for it when you're required to give it to me for free.  If I'm the kind of person who wants to pay for it, great, but you'll probably go out of business if you rely on finding that kind of person.

So, in order to induce me, a third party, to become a second party and enter into a sales agreement with you, clearly you should be offering some added value; warranty, support, installation services, hosting, etc.


答:
If you have more than one developer making changes to your schema, then you might need a tool like Redgate SQL Compare or similar create change scripts between environments.

Although more of an admin tool than a developer tool, dbcc inputbuffer({spid}) will get the current / last executed sql statement on a per connection level. It won't however return anything useful on the current connection (dbcc inputbuffer(@@SPID) returns dbcc inputbuffer(@@SPID) :P))

At a server / audit level, SQL Server Audit can assist with tracking changes to your schema.

Title: SQL Server Management Studio Show last executed query

Body: I am looking for a way for SQL Server Management studio to show me the last SQL query that was run. For example, when I make modifications to a table in the designer mode, I will eventually want to make the same changes to the production DB without recreating the entire table. I'm looking for functionality similar to PHPMyAdmin for MySQL which tells you the last query ran and the results of the query at the top of the page after the modifications are complete.</p>


答:
Ethically, a code "idea" such as a small pattern or even a custom UI control is typically OK to retain for future use elsewhere. Many of us keep "CommonLib" source libraries containing these kinds of things in a readily re-usable way. Even if not, you remember how you did it, and if it's a good way to do it then do it in other situations where it applies. It's ridiculous to try to assert that you shouldn't be a good coder on one project for one client/employer (including yourself) because you were a good coder on another project and shouldn't plagiarize the ideas you had while working for the other guy. It's called job experience.

Legally, it depends on what you signed when you were hired/contracted. Some companies force workers to sign lifetime NDAs with wording that could be construed to mean "you can't write a line of code for anyone else based on any knowledge of our own codebase". A good lawyer can get the lawsuit thrown out even if you did sign that (seriously, are you expected to hit yourself over the head with a baseball bat until you can't remember working there? Much as I might like to do so for some of my prior jobs it's a completely unreasonable expectation), but it'll still be a pain.

Big no-nos both legally and ethically include copying binaries or source that you specifically developed for one employer and pasting them into a solution for another. While patterns and algorithms are well-known, as are best-practice architectures, coding conventions, etc that can make bits and pieces of two competitors' codebases look similar, a source file that was copied verbatim is plagiarism, plain and simple, and an unmitigated violation of implied or explicit copyright as well as any NDA any competent corporate lawyer would draft. You would have to have stipulated, in anything you signed that would restrict this, at every employer you ever worked for, that you are entitled to retain a "portfolio" of general-purpose code that remains your property independent of your employment. You'd have to be damn good for an employer to still want you if you insisted on that, and the line would have to be very clearly drawn as to what you could and could not claim as your own.

Another fuzzy area where you might be OK, maybe not, is UI "look and feel". The bottom line is similar; while the basic GUI controls like buttons, textboxes, checkboxes, radio buttons, etc were all designed for minimum "surprise factor" and are in the public domain as UI concepts, and there are well-known combinations of same that similarly reduce the learning curve through familiarity, it's probably a bad idea to take a novel UI concept that one company developed (under your watch) for doing a particular task, and bringing it verbatim over to your next job where a new project has a similar need. The Telerik and DevExpress controls, and other third-party non-Microsoft proprietary UI libraries, are sold for money, and so are copywritten heavily; creating a carbon copy, even if you typed every character of the source file yourself, can get you in trouble legally; you have to prove that every single character was written without any more than a cursory (user-level) knowledge of how the third-party control works.

Title: Can I use code in my own projects that I have written for someone else?

Body:
In the past I did a freelancing project for someone where I wrote a couple of image filters. Nothing fancy, and a very very low cost project for them. I was wondering, if I wish to use these in a project of mine, would I legally/ethically be allowed to do that? If I couldn't use the exact code, could I at least use the general data I used to make them. (I modeled the filters in Photoshop and then coded a duplicate filter in a programming language.)

My specific work was done through freelancer.com and we had no special terms or conditions.


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

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

答: going out a bit on a limb here - void functions. a function always does something, hence it should either return the result or some other bit of information regarding its success or failure. </p>


问:
Parameter order: size, count or the other way round
I hope this is the right forum for this ... Well, in C, the standard library uses usually (void* buffer, int size) when referring to some data buffer. I wonder if there is a rationale for this order instead of (int size, void* buffer). I couldn't think of any good reason, and it seems to be an arbitrary choice, but I'm curious to here if there is some deeper meaning behind this order.

答: In C you can't do object->method(value), so it's idiomatic to put the "object"—the thing whose state you're changing—as the first parameter, and prefix the function name with the "class."  The C standard library makes a lot more sense when you think about it that way.  For example, strcpy(dest, src) reads as dest->cpy(src), where dest is a str object.


问:
How to explain that sample size does not influence project length
We have big enterprise projects they normally involve copying data from a source database to a destination database and then setting up a number of additional applications that sync this data etc.

The last project contained 250,000 items (rows of data). The next project will only contain 4,000 items. Project managers / business people believe the project should be 1/10 the time to complete because its only a fraction of the size of the last project.

What is a good analogy I can use to explain that writing code to transfer data from one system to another takes the same amount regardless of the number items - writing it for 1 item or for 100,000,000 will take roughly the same amount of time from a programming point of view.

答:
Put it into manager speak.

If you build a machine to make widgets at 1 widgets per second,
it does not matter if you use it to make 100 widgets
or 10000 widgets, the machine itself takes the same time to build.

the difference is at run time, not build time.

All management classes work on problem like this with hypothetical widget factories.


问:
Is it frowned upon to release works in progress to github/sourceforge/bitbucket/etc?
Long story short, I've spent the last two years in an entirely new career, transitioning from academia to a data analyst role (working towards a data scientist). Before starting at my current company, I knew next to nothing about coding, save for teaching myself SQL for a few hours per week over a couple of months. Besides SQL, I have since become conversant in Perl, have used PHP a bit here and there, and have made some headway into learning other languages (primarily Java and C). So, I still have a lot of catch-up work to do.

In order to teach myself things, I've built a few side projects--a lot more sophisticated than "Hello World, my name is $name.", but not as complicated as, say, Minecraft or a device driver. I'd like to release the code for them in order to learn from constructive feedback and to build a portfolio to sit alongside my resume. However, a lot of these things are works in progress and, to be honest, I feel some trepidation at putting code out there for all to see that's not completely, 100% "done" and polished.

Am I worrying over nothing? If not, is there some minimal polish threshold a project should have before releasing it as open source?

答:
The things you need to worry about are:

Can I build it in one step?

Is there a clear description of the purpose for the project?

Are the working features known?

If your project does 100% of what it's been coded to do, then release it. You'll probably never get to the point where you are 100% satisfied with it and never want to improve it.

It would also be great to make sure they have Unit tests as that is also a form of documentation and proof that your project is "good."

In all seriousness though if your projects are very specific to things you've worked on in the past most people won't find them unless you go out of your way to link to it from other forums. But if it solves a problem current developers are having it has the potential to take off.


答:
As long as your project builds and has documentation on what works and what is broken or to be done, I consider that it can be released as an alpha/beta.

In fact, this is what many open-source projects do; if your work has potential to solve a larger problem, this can attract developers to work on the missing/incomplete features.

Title: Is it frowned upon to release works in progress to github/sourceforge/bitbucket/etc?

Body:
Long story short, I've spent the last two years in an entirely new career, transitioning from academia to a data analyst role (working towards a data scientist). Before starting at my current company, I knew next to nothing about coding, save for teaching myself SQL for a few hours per week over a couple of months. Besides SQL, I have since become conversant in Perl, have used PHP a bit here and there, and have made some headway into learning other languages (primarily Java and C). So, I still have a lot of catch-up work to do.

In order to teach myself things, I've built a few side projects--a lot more sophisticated than "Hello World, my name is $name.", but not as complicated as, say, Minecraft or a device driver. I'd like to release the code for them in order to learn from constructive feedback and to build a portfolio to sit alongside my resume. However, a lot of these things are works in progress and, to be honest, I feel some trepidation at putting code out there for all to see that's not completely, 100% "done" and polished.

Am I worrying over nothing? If not, is there some minimal polish threshold a project should have before releasing it as open source?


问:
Is it a good idea to design an architecture thinking that the User Interface classes can be replaced by a command line interface?
In Code Complete page 25, it's said that it's a good idea to be able to easily replace the regular user interface classes by a command line one.

Knowing its advantages for testing, what about the problems it may bring?

Will this extra work really pay off for web and mobile projects? What about small and medium projects; do the same rules apply?
What if it makes your design more complex?

答:
Completely aside from testing, the obvious advantage to this approach is that it will make your project automatable and scriptable.  If I'm able to send command-line commands to a program, I can write up a script to perform complicated tasks much more easily (and more reliably!) than I could create a macro to automate the same thing on a GUI.

Whether or not that's actually worth doing, of course, depends entirely on whether or not you have a lot of users who would want to automate your program.


答:
Yes it's almost always a good idea.

If you follow this approach you will not likely have a business logic or data access in a same thread as GUI, and behind some GUI handler. This reason alone is worth investing in.

Title: Is it a good idea to design an architecture thinking that the User Interface classes can be replaced by a command line interface?

Body:
In Code Complete page 25, it's said that it's a good idea to be able to easily replace the regular user interface classes by a command line one.

Knowing its advantages for testing, what about the problems it may bring?

Will this extra work really pay off for web and mobile projects? What about small and medium projects; do the same rules apply?
What if it makes your design more complex?


问:
Using a GPLv3 library in a freemium business model
I read several related questions about the use of GPLv3 in a commercial app but they don't say anything about a freemium app. I would like to use a GPLv3 library in two apps, a free one (with limited features) and a paid one.

Basically, the free app will allow to use the library without limitations, and the paid one will include it as well as other unrelated features.

I will release the free app under GPLv3 but do I need to release the paid one under the same license?

I don't want to release the whole source code of my paid app (for obvious reasons), as the other features don't use the library in any way. It would just be more convenient for users who bought the full version to have all features in a single app instead of putting the library in a separate one.

答:
If you own the copyright to all the source code, you can offer it under two different licenses.  This is called dual licensing, and is fairly common.

Edit:

If you're talking about a 3rd party library written by someone else and licensed under the GPLv3, you can't use that in a work that you're distributing and licensing in a way that's not compatible with the GPLv3.


答: I think it is a good idea. Additionally being able to write a second, command line front end, ultimately proves the business logic is totally decoupled to any particular application server architecture.</p>


答: It's not extra work, just different work.  If you do it right, not only will it not make it more complex, it will make it simpler because it will force you to decouple your design.  Whether or not you actually implement the CLI, your design will be better off for making it possible to do so.


答:
From here:

If I use a piece of software that has been obtained under the GNU GPL, am I allowed to modify the original code into a new program, then distribute and sell that new program commercially?

You are allowed to sell copies of the modified program commercially, but only under the terms of the GNU GPL. Thus, for instance, you must make the source code available to the users of the program as described in the GPL, and they must be allowed to redistribute and modify it as described in the GPL.

These requirements are the condition for including the GPL-covered code you received in a program of your own.

and also:

A system incorporating a GPL-covered program is an extended version of that program. The GPL says that any extended version of the program must be released under the GPL if it is released at all.

Combining these two statements might lead to the following conclusion:

When you sell your app, you're obliged to give all the code to any of your users who asks for it. It's bound by GPLv3 too. They would then be free to alter it as they see fit and redistribute at their leisure (or rather "as described in the GPL").

Title: Using a GPLv3 library in a freemium business model

Body:
I read several related questions about the use of GPLv3 in a commercial app but they don't say anything about a freemium app. I would like to use a GPLv3 library in two apps, a free one (with limited features) and a paid one.

Basically, the free app will allow to use the library without limitations, and the paid one will include it as well as other unrelated features.

I will release the free app under GPLv3 but do I need to release the paid one under the same license?

I don't want to release the whole source code of my paid app (for obvious reasons), as the other features don't use the library in any way. It would just be more convenient for users who bought the full version to have all features in a single app instead of putting the library in a separate one.


问:
Is it easier to write robust code in compiled, strictly-typed languages?
I'd like to read the opinion of experts on whether compiled, strictly-typed languages help programmers write robust code easier, having their backs, checking for type mismatches, and in general, catching flaws in compile time that otherwise would be discovered in runtime ?

Has unit testing in loosely typed, interpreted languages need to be more thorough because test cases need to assess things that in a compiled languages wouldn't simply compile ?

Need the programer in compiled, strictly-typed need to write less code since he/she doesn't have to constantly check for correct types ( instance of operator ) since the compiler catches those things ( the same applying to misspelled variable names or uninitiated variables ) ?

NOTE: by strictly typed language I mean languages that force you to declare variables and assign a type to them in order to be able to use them, and once a variable is declared, you cannot change its type or assign incompatible type values.

```<code>int myInt = 0;
String myString = "";
myInt = myString; // this will not fly in a strictly typed language
myInte = 10;   // neither will this ( myInte variable doesn't exist )
</code>```

答:
I'd like to read the opinion of experts on whether compiled, strictly-typed languages help programmers write robust code easier, having their backs, checking for type mismatches, and in general, catching flaws in compile time that otherwise would be discovered in runtime ?

For some programs they do.

For some programs they require you to do things that are not really necessary to enable static checks that don't catch anything.

Experts have no consensus. Personally, I favor traditional statically typed languages for most things.

Has unit testing in loosely typed, interpreted languages need to be more thorough because test cases need to assess things that in a compiled languages wouldn't simply compile ?

Not necessarily. The general consensus is that unit tests are the quickest and easiest way to do that, but there is some debate if you need any more unit tests to effectively catch those errors or if the normal tests you'd write to test the functionality would catch it.

Need the programer in compiled, strictly-typed need to write less code since he/she doesn't have to constantly check for correct types ( instance of operator ) since the compiler catches those things ( the same applying to misspelled variable names or uninitiated variables ) ?

If you're doing instanceof in dynamic languages, that is a code smell (imo). So if you consider type annotations, type declarations, or variable declarations to be 'code' then yes, you'll naturally write more code to do the overhead. If not, then it is debatable.

The main thing is that it is never so clear cut. Tooling is generally easier for statically typed languages. Type annotations help readability of code (so some argue). Not having type annotations helps readability of code (so some argue). There's no good quantitative measurement to help. No consensus.


问:
Rails - How to use modal form to add object in one model, then reflect that change on main page?
I'm working on a Rails app and I've come across a situation where I'm unsure of the cleanest way to proceed.

I posted a question on SO with code samples and such - it has received no answers, and the more I think about the problem, the more I think I might be approaching this the wrong way. (See the SO question at https://stackoverflow.com/questions/9521319/how-to-reference-form-when-rendering-partial-from-js-erb-file)

So, in more of a generic architecture type question: Right now I have a form where a user can add a new recipe. The form also allows the user to select ingredients (it uses a collection_select which contains Ingredient.all). The catch is - I'd like the user to be able to add a new ingredient on the fly, without leaving the recipe form.

Using a hidden div and some jQuery/AJAX, I have a link the user can click to popup a modal form containing ingredients/new.html.erb which is a simple form. When that form is submitted, I call ingredients/create.js.erb to validate the ingredient was saved and hide the modal div. Now I am back to my recipe form, but my collection_select hasn't updated.

It seems I have a few choices here:

try and re-render the collection_select portion of the form so it grabs a new list of ingredients. This was the method I was attempting when I wrote the SO question. The problem I run into is the partial I use for the collection_select needs the parent form passed in, and when I try and render from the JS file I don't know how to pass it the form object.

Reload the recipe form. This works (the collection_select now contains the new ingredient), but the user loses any progress they made on the recipe form. I would need a way to persist the form data - I thought about manually passing the values back and forth, but that is sloppy and there has to be a better way...

Try and manually insert the  tags using jQuery - this would be simple, but because I'm allowing for multiple ingredients to be added, I can't be certain what ID to target.

Now, I can't be the only person to have this issue - so is there an easier way I'm missing? I like option 2 above, but I don't know if there's an easy way to grab the entire params hash as if I had submitted the main recipes form.

Hopefully someone can point me in the right direction so I can find an answer to this... If this doesn't make any sense at all, let me know - I can post code samples if you want, but most of the pertinent code is up on the SO question.

Thanks!

答:
I haven't done this with creating new items, but I have done something similar for edits.  I'm not sure if this is the 'cleanest' way of doing it, but it worked for me.

The following works with Rails 3.1, jQuery and coffeescript.  If you're using Rails 3.2, I think you now have to put .erb on the end of the coffeescript file.  You can use js2coffee to convert the below easily (if you're not using coffeescript).

I defined the dialog code (in /app/views/drops/edit.js.coffee) as:

```<code>$("#edit-drop-form").dialog
  autoOpen: true
  height: 460
  width: 380
  title: 'Edit Drop'
  buttons:
    "Cancel": ->
      $("#edit-drop-form").dialog "close"
    "Save": ->
      $.post "/drops/<%= @drop.id %>.json", $("#edit-drop-form form").serializeArray(), (data, text, xhr) ->
        if (xhr.status == 200)
          # Update the DOM here!
          $("#notice").empty().append("Drop updated successfully!")
          $("#edit-drop-form").dialog "close"
  open: ->
    $("#edit-drop-form").html "<%= escape_javascript( render('form') ) %>"
</code>```

In the above example, the 'form' partial will be rendered in the popup and a json handler in the 'update' action of my Drops controller will process the request.

To change this for creating new items, add a 'json' handler for the create action and have a similar javascript file to the above (but called new.js.coffee).  You'll also need to adjust the path for the 'post' to the create action.

Where my comment says "Update the DOM here", is where you'll want to update your select.
Simply create a json handler for the 'index' action of IngredientsController, call '$.get "/ingredients.json"' and replace the contents of your select based on the data that returns.

Body:
I haven't done this with creating new items, but I have done something similar for edits.  I'm not sure if this is the 'cleanest' way of doing it, but it worked for me.

The following works with Rails 3.1, jQuery and coffeescript.  If you're using Rails 3.2, I think you now have to put .erb on the end of the coffeescript file.  You can use js2coffee to convert the below easily (if you're not using coffeescript).

I defined the dialog code (in /app/views/drops/edit.js.coffee) as:

$("#edit-drop-form").dialog
  autoOpen: true
  height: 460
  width: 380
  title: 'Edit Drop'
  buttons:
    "Cancel": ->
      $("#edit-drop-form").dialog "close"
    "Save": ->
      $.post "/drops/<%= @drop.id %>.json", $("#edit-drop-form form").serializeArray(), (data, text, xhr) ->
        if (xhr.status == 200)
          # Update the DOM here!
          $("#notice").empty().append("Drop updated successfully!")
          $("#edit-drop-form").dialog "close"
  open: ->
    $("#edit-drop-form").html "<%= escape_javascript( render('form') ) %>"

In the above example, the 'form' partial will be rendered in the popup and a json handler in the 'update' action of my Drops controller will process the request.

To change this for creating new items, add a 'json' handler for the create action and have a similar javascript file to the above (but called new.js.coffee).  You'll also need to adjust the path for the 'post' to the create action.

Where my comment says "Update the DOM here", is where you'll want to update your select.
Simply create a json handler for the 'index' action of IngredientsController, call '$.get "/ingredients.json"' and replace the contents of your select based on the data that returns.


问:
Is Object Oriented Programming a solution to complexity?
Do you think Object Oriented Programming is a solution to complexity. Why? This topic may be a bit controversial but my intentions to know the answer of Why from the experts here !</p>

答:
To some degree...

Why? Because it facilitates very logical modularity. At least in comparison to procedural programming where it's all too tempting to just write huge piles of spaghetti code.


答:
Need the programer in compiled, strictly-typed need to write less code since he/she doesn't have to constantly check for correct types ( instance of operator ) since the compiler catches those things ( the same applying to misspelled variable names or uninitiated variables ) ?

I write almost exclusively in dynamically typed languages, and I almost never have to check for correct types. First, the program will throw a type or no method error if I use the wrong type somewhere, and second, I tend to use the types I intend to use where I intend to use them.

An edit on that first point based on a comment below: yes, the program will throw that error "at runtime". But since I run portions of the program easily as often as I would compile in a statically typed language (possibly more often), this isn't particularly relevant. "Runtime" doesn't mean "production", it means "when I run my unit tests". When I run my unit tests, if I am calling a method that doesn't exist on a type, I'll get a no method error.

While it is true that people make mistakes and sometimes write code that divides a char by an array, this is less common than you would think. Most code is fairly type safe by design... if it weren't mostly type consistent, it wouldn't work and wouldn't pass its unit tests.

Similarly, in my experience, unit testing doesn't need to be any more thorough in say, Ruby than it does in Java... I use unit testing to test the behavior of methods and classes, not for type checking. The type checking is implicit... type mismatches throw errors that indicate errors in my code that should be solved by better code, not by adding type checks.

A further edit based on another comment -- no, my unit testing does not have to be more extensive and I do not have to write more code to make sure I didn't misspell a variable name inside a nested conditional.

If I needed a variable to change values based on some logic branch and it doesn't because I accidentally declared a new variable, I'll catch that while unit testing behavior, not unit testing variable names and type checking. I would write the same unit test in a static-explicit language, and while I might get a compile error instead of a failed test the end result is the same: I'll see the mistake and fix the code when I run the unit test that is checking that I get the right behavior, not that I'm using the right types and variables.

If I am writing code where that kind of mistake could slip through my unit tests, my problem is not that I'm using a dynamic-implicit language, it's that I'm writing bad code with untracked side-effects. Using a static-explicit language isn't going to help me there, it's just going to give me a false sense of security about my bad code.

Title: Is it easier to write robust code in compiled, strictly-typed languages?

Body:
I'd like to read the opinion of experts on whether compiled, strictly-typed languages help programmers write robust code easier, having their backs, checking for type mismatches, and in general, catching flaws in compile time that otherwise would be discovered in runtime ?

Has unit testing in loosely typed, interpreted languages need to be more thorough because test cases need to assess things that in a compiled languages wouldn't simply compile ?

Need the programer in compiled, strictly-typed need to write less code since he/she doesn't have to constantly check for correct types ( instance of operator ) since the compiler catches those things ( the same applying to misspelled variable names or uninitiated variables ) ?

NOTE: by strictly typed language I mean languages that force you to declare variables and assign a type to them in order to be able to use them, and once a variable is declared, you cannot change its type or assign incompatible type values.

```<code>int myInt = 0;
String myString = "";
myInt = myString; // this will not fly in a strictly typed language
myInte = 10;   // neither will this ( myInte variable doesn't exist )
</code>```


问:
Is it ever too early to learn a new language?
Personal context: I've been learning C++ formally the last 6 months at university. Prior to this I dabbled in JavaScript for a year. Now I am considering learning Python during a month off school.

By splitting my focus early in the learning process am I degrading the efficiency of my learning? Should I spend the month off continuing in C++? Or is it never too early to learn a new language?

答:
Can't you do both??
I would do a project in C++ and learn bits of Python (just because it is so awesome), you could solve problems at ProjectEuler.net using Python

In general, I think its a bad idea to learn a language, leave it and start learning a new one. One should be flexible working with different paradigms at the early stages. But that is just what I think.


答:
My experience with Python is limited to some play code only slightly more complex than hello world, so this won't be a very in-depth answer for python specifically, but I can tell you this:

The differences between the languages is in details like the syntax and certain language specifics will be different (like the different ways errors are handled, I/O capabilities and how compilers convert your input into something executable), but C++ and Python both offer the same paradigms, so problem solving can be done in much the same way with both languages. Both C++ and Python are  Imperative and Object Oriented, so you're probably going to pick up python quite fast if you're comfortable with C++ once you've mastered the new syntax using problem solving techniques you've picked up with C++. If you want to, you can use Python for functional programming as well, but I've never touched that part, so I can't tell you much about it.

Is it too early? I can't really tell from your story in a definitive yes or no.
Are you already confident enough to write full (GUI) applications with C++? (i.e. use libraries, more complex language features like generics and/or templating etc.)
I think that learning a new language paradigm is much harder than learning a new language in the same paradigm family. When you step out into new paradigm territory, you'll have to spend much more time for getting a good idea of how to solve problems with that paradigm.
Between OO languages there are differences as to how inheritance is dealt with, and how data is passed in the memory when you pass a parameter/argument to a function affecting performance. But to get going these are usually of minor concern at first.

My guess is that if you're confident enough with C++ to do something more than hello world in a fancy way, you're ok for launch.
Learning many languages superficially will help you understand code samples regardless of the language used, but creating your own code requires a bit more understanding of how the languages work and how they differ from each other.

P.S. When I want to learn how to use a new language superficially, I'll usually try the following things to get a feel for the language syntax and superficial workings:

Hello world (Text on screen)

Hello world written to a file (teaches you the basics on file I/O for that language, and very often other kinds of I/O as well)

Doing some standard calculations with different bases (10, hex, octal), both integer and floating point. (teaches you about truncation and number notation)

Try to use some graphical library to show hello world in a fancy dialog. (teaches you how to use libraries and external code)

Title: Is it ever too early to learn a new language?

Body:
Personal context: I've been learning C++ formally the last 6 months at university. Prior to this I dabbled in JavaScript for a year. Now I am considering learning Python during a month off school.

By splitting my focus early in the learning process am I degrading the efficiency of my learning? Should I spend the month off continuing in C++? Or is it never too early to learn a new language?


问:
Is it typical for a unit test suite to be larger than the code it tests?

Possible Duplicate:

  What is a normal “functional lines of code” to “test lines of code” ratio?

I've found that more often than not, when you write lots of unit tests, and have good coverage (80% or so), the test suite ends up being larger than the code itself.

Do my observations match that of everyone else?

I've also found that more often than not, a the larger the test suite, the harder it is to maintain the test suite.  What ends up happening is that the test suite rots away as for every X lines you change you make to the code, X^2 lines need to change in the test suite.

Is this an attribute of unit test suites in general?  Or am I just working on crappy unit test suites?

答:
This may indeed happen when you write lots of unit tests and do a lot of TDD. When you come to a point where the test suite hinders you in making changes to a specific function in your code, then your test suite most probably contains too many (similar-looking) calls to this same function of your code. That's almost always a sign for your test suite not beeing "DRY" any more. My suggestions to avoid that::

refactor your test suite regularly to make it more DRY. Bundle your function calls to the code if they are looking similar in a central function, bundle the test data creation if the test data is reused for more than one test, write supporting functions to allow the comparison of complex objects with the expected values in less lines of code, and so on.

write parameterized, data driven tests. Most modern unit test frameworks allow you to write a test function once and supply several sets of test data to it. If your framework does not have direct support for this technique, you can easily build it manually.

It may also be a good idea to study some "classic" test theory (see, for example, here) how to systematically design as few test cases as possible to achieve a high coverage.


答:
Is it ever too early to learn a new language?

I would say yes. If you're still wrapping your head around the very concept that the computer might actually do what you tell it, then learning a second language will probably just confuse you.

But if you are past the point where you realize that the computer does exactly what you tell it to, no matter how stupid it is, then chances are that you have a reasonable enough grasp of your first language that looking at a second (and third!) language doesn't break your focus.


答:
I expect you'll get some better answers shortly, but here's a simple one:

OOP helps* with complexity by modeling software in a way closer to the way we model everything else in the world.  It's just generally easier to image a ball object interacting with a wall object than it is to imagine a series of routines and data structures to do the same thing, since it's closer to how we interact with the real world.

*Because nothing can 'solve' complexity

Title: Is Object Oriented Programming a solution to complexity?

Body: Do you think Object Oriented Programming is a solution to complexity. Why? This topic may be a bit controversial but my intentions to know the answer of Why from the experts here !</p>


答:
Bigger tests than code?

It depends.

Sometimes the test will be more complex.

Sometimes the code will be more complex.

Refactoring to Simplify Code and Test Cases

It may be worth considering some simplifications and refactoring if things are getting exponential on you.

I have worked with several maintenance projects that were littered with God classes.  These tended to be much more manageable when refactored into smaller classes.

Some classes are not minimal and a search for repeated code, and refactoring to eliminate repetition has the potential to reduce your test surface significantly.

Black Box vs. Glass Box Testing

One issue that arises is that of TDD methodology.  When the user story changes, that produces more tests.  On initial execution, they fail, and more code is written to make them pass.  When they pass, the user story is implemented and we ship.  Naturally, in real life, things might not be this pure.  However, I guess it might be worth asking how much does the user story elaborate the test cases?  Are the test cases functional, black box testing based on exercising the valid and invalid inputs?

It sounds from your description that some of the test cases are aimed at statement coverage.  I like statement coverage, but there are several additional kinds of coverage as well.  There are methods to optimize coverage test cases that you should perhaps consider if you find that part of your high test case count is due to brute forcing things to get through to every line.

Code Coverage Types

The following link illustrates with some cool graphics several types of coverage.  I don't endorse or have an opinion about their product, just their diagram.

http://www.atollic.com/index.php/trueanalyzer/types-of-code-coverage-analysis

In their example, they show modified condition/decision coverage and determine that for the code they show, four test cases both execute every statement, and cause the branching into the if statement for every kind of condition that might occur.  Discovery of test cases when the decision criteria are nested comparisons like

```<code>if (a < 5) // d1
   if (b < 10) //d2
      a = 7;

if ((a + b) < 8) //d3
   c = 5;
</code>```

can be trickier to analyze for test case values, but you know you will need a test case with a < 5 and a >=5 from the very first if, and also b < 10 and b >= b from the second if.

Because in some paths a will be the input, and others a will be a modified value (a=7), you  may need to use a technique called symbolic execution where the third if is analyzed in terms of a' and a''.  To execute c = 5, you will need a test case where the condition is satisfied.  You will also want to run a test where c is never assigned.

A list of test cases that I think covers everything is:

```<code>T1: a=4, b=9 => a'=4, a''=7, covers d1=true, d2=true, d3=false
T2: a=5, b=9, covers d1=false
T3: a=4, b=10, covers d2= true
</code>```

But how do we get d3 covered?
Assigning a in the second if statement makes the analysis more complicated unless we do this with it.

```<code>((a' + b) < 8), ((a'' + b) < 8)

((a' + b) < 8), ((7 + b) < 8)  // Remember a'' = 7

((a' + b) < 8), (b < 1)  // Remember a'' = 7
</code>```

T4: a=1, b=0, covers d3=true

Symbolic execution is a test related technique that you can use to reduce the test cases needed to perform decision coverage.  It is not an easy read, but a classic paper on the subject is:

http://www.cs.uiuc.edu/class/sp11/cs477/king76symbolicexecution.pdf

Apologies in advance if this diverts too far from your original question.  I hope it will be of some use.

Title: Is it typical for a unit test suite to be larger than the code it tests?

Body:
Possible Duplicate:

  What is a normal “functional lines of code” to “test lines of code” ratio?

I've found that more often than not, when you write lots of unit tests, and have good coverage (80% or so), the test suite ends up being larger than the code itself.

Do my observations match that of everyone else?

I've also found that more often than not, a the larger the test suite, the harder it is to maintain the test suite.  What ends up happening is that the test suite rots away as for every X lines you change you make to the code, X^2 lines need to change in the test suite.

Is this an attribute of unit test suites in general?  Or am I just working on crappy unit test suites?

Body:
Bigger tests than code?

It depends.

Sometimes the test will be more complex.

Sometimes the code will be more complex.

Refactoring to Simplify Code and Test Cases

It may be worth considering some simplifications and refactoring if things are getting exponential on you.

I have worked with several maintenance projects that were littered with God classes.  These tended to be much more manageable when refactored into smaller classes.

Some classes are not minimal and a search for repeated code, and refactoring to eliminate repetition has the potential to reduce your test surface significantly.

Black Box vs. Glass Box Testing

One issue that arises is that of TDD methodology.  When the user story changes, that produces more tests.  On initial execution, they fail, and more code is written to make them pass.  When they pass, the user story is implemented and we ship.  Naturally, in real life, things might not be this pure.  However, I guess it might be worth asking how much does the user story elaborate the test cases?  Are the test cases functional, black box testing based on exercising the valid and invalid inputs?

It sounds from your description that some of the test cases are aimed at statement coverage.  I like statement coverage, but there are several additional kinds of coverage as well.  There are methods to optimize coverage test cases that you should perhaps consider if you find that part of your high test case count is due to brute forcing things to get through to every line.

Code Coverage Types

The following link illustrates with some cool graphics several types of coverage.  I don't endorse or have an opinion about their product, just their diagram.

http://www.atollic.com/index.php/trueanalyzer/types-of-code-coverage-analysis

In their example, they show modified condition/decision coverage and determine that for the code they show, four test cases both execute every statement, and cause the branching into the if statement for every kind of condition that might occur.  Discovery of test cases when the decision criteria are nested comparisons like

if (a < 5) // d1
   if (b < 10) //d2
      a = 7;

if ((a + b) < 8) //d3
   c = 5;

can be trickier to analyze for test case values, but you know you will need a test case with a < 5 and a >=5 from the very first if, and also b < 10 and b >= b from the second if.

Because in some paths a will be the input, and others a will be a modified value (a=7), you  may need to use a technique called symbolic execution where the third if is analyzed in terms of a' and a''.  To execute c = 5, you will need a test case where the condition is satisfied.  You will also want to run a test where c is never assigned.

A list of test cases that I think covers everything is:

T1: a=4, b=9 => a'=4, a''=7, covers d1=true, d2=true, d3=false
T2: a=5, b=9, covers d1=false
T3: a=4, b=10, covers d2= true

But how do we get d3 covered?
Assigning a in the second if statement makes the analysis more complicated unless we do this with it.

((a' + b) < 8), ((a'' + b) < 8)

((a' + b) < 8), ((7 + b) < 8)  // Remember a'' = 7

((a' + b) < 8), (b < 1)  // Remember a'' = 7

T4: a=1, b=0, covers d3=true

Symbolic execution is a test related technique that you can use to reduce the test cases needed to perform decision coverage.  It is not an easy read, but a classic paper on the subject is:

http://www.cs.uiuc.edu/class/sp11/cs477/king76symbolicexecution.pdf

Apologies in advance if this diverts too far from your original question.  I hope it will be of some use.


问:
What relationship do software Scrum or Lean have to industrial engineering concepts like theory of constraints?
In Scrum, work is delivered to customers through a series of sprints in which project work is time boxed to a fixed number of days or weeks, usually 30 days.  In lean software development, the goal is to deliver as soon as possible, permitting early feedback for the next iteration.

Both techniques stress the importance of workflow in which software work product does not accumulate in development awaiting release at some future date.  Both permit new or refined requirements and feedback from QA and customers to be acted on with as little delay as possible based on priority.

A few years ago I heard a lecture where the speaker talked briefly about a family of concepts from industrial engineering called theory of constraints.  In the factory, they use an operations model based on three components: drum, buffer, and rope.  The drum synchronizes work product as it flows through the system.  Buffers that protect the system by holding output from one stage as it waits to be consumed by the next. The rope pulls product from one work station to the next.

Historically, are these ideas part of the heritage of Scrum and Lean, or are they on a separate track?

It we wanted to think about Scrum and Lean in terms of drum-buffer-rope, what are the parts?

Drum = {daily scrum meeting, monthly release)?

Buffer = {burn down list, source control system)?

Rope = { daily meeting, constant integration server, monthly releases}?

Industrial engineers define work flow in terms of different kinds of factories.

I-Factories: straight pipeline. One input, one output.

A-Factories: many inputs and one output.

V-Factories: one input, many output products.

T-Plants: many inputs, many outputs.

If it applies, what kind of factory is most like Scrum or Lean and why?

答:
Agile is really just a set of principles (see here).  Scrum is just one tool to try to adhere to those principles.

Another agile/lean tool which does rely heavily on theory of constraints in Kanban.  Where one of the key points is to limit work in progress (WIP) in order to improve output (See here).

Its worth noting though that Kanban is only agile if you choose to use it that way, as its much less prescriptive of process then scrum is, and in theory could be implemented in a waterfall SDLC.


答:
Well of course it is.

No doubts about it, it is sometimes too early to learn a new programming language.

The simplest case is if an el-stinko language comes out and before anyone points out its unsuitability, by learning it you damage your brain.  A couple that come to mind include BASIC, FORTH, and APL.

For a more complicated case, one of the great computer scientists has described this problem which very briefly stated is that practice makes permanent, and there are many disciplines that should be learned before learning computer languages so that the language does not distort the more fundamental understanding.  In his words:

The tools we use have a profound and devious influence on our thinking
  habits, and therefore on our thinking abilities.

The opponent of just diving into to programming is named Edsger Dijkstra and he had a very distinguished career.  He was awarded the ACM Turing Award with the following citation:

For fundamental contributions to programming as a high, intellectual
  challenge; for eloquent insistence and practical demonstration that
  programs should be composed correctly, not just debugged into
  correctness; for illuminating perception of problems at the
  foundations of program design.

The paper where he blasts premature learning of programming languages is:

"On the Cruelty of Really Teaching Computer Science"
http://www.cs.utexas.edu/users/EWD/ewd10xx/EWD1036.PDF

Also, please don't flame me, I am just the messenger.


问:
Does there exist a design-pattern for this problem?
I have a big database of data which we can consider today's system. The data has a web front-end which allows my users to update the data. Let's call this "original solution"

When new users come in they come as a set of new users. These users need their own data and their own web front-end. Let's call this a "solution". Originally we have 1 solution (the original solution), however I now need the same solution for a different set of users.

Some factors that need to be considered in the design:

The original solution may choose to implement other solutions updates and inserts on the data.

Any solution may choose to receive updated and inserted data from the original solution.

Updates between solutions should be easily shareable.

Now the easiest solution would be just to replicate the entire database and have some sort of process to write and read data between solutions. This however has a really high overhead when it comes to duplicate data, storage needs and so on. I would imagine storing some kind of delta between the data would be better?

I imagine a possible solution would be to design the architecture much like a source code control system with branches would be? When a new solution is implemented we branch the original solution. The different updates in branches can easily be updated into the main branch and vice-versa.

Is there any tips in how I can easily clone the data in the original solution to a new solution without replicating the actual database? Perhaps a design pattern I can use in the implementation?

答: You could implement the command pattern to manage resp. record the actions done on the original solution, then run the same commands on the other solutions.</p>


答:
It depends.

Often we partition our programs as model/view/controllers or model/view/view/model.  It seems that the model should permit command line access, but I am not as sure about the controller.  Naturally, the view is what is being replaced.

Some difference may exist based on tool chain.  Code Complete is a Microsoft Press book, so perhaps you are using Microsoft technologies for this GUI?  If so, I think there might be a check box when you create the app for exposing interfaces via COM or DCOM.  For some Microsoft technologies, I think resource tables and message passing are pretty intensively coupled with anything the Wizards help you rapidly prototype.  I think it is getting better, but if you are maintaining MFC or Forms, it might hurt a bit.

In some cases your GUI based program might be a wrapper around a management interface or might have so little logic of its own, that there is not much to control by command line interface.   Building a separate console app might be quicker and still let you script, test or use what is important.

The key point I guess is that the suggestion is not a rule.  If you follow it, you should get easier unit and acceptance testing or a fall back interface for when you or a customer might prefer typing instead of clicking.  If it pays for itself, do it.  Good luck.


答:
Object-oriented programming has roots that can be traced to the 1960s. As hardware and software became increasingly complex, manageability often became a concern. Researchers studied ways to maintain software quality and developed object-oriented programming in part to address common problems by strongly emphasizing discrete, reusable units of programming logic.

An object-oriented program may thus be viewed as a collection of interacting objects, as opposed to the conventional model, in which a program is seen as a list of tasks (subroutines) to perform. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent 'machine' with a distinct role or responsibility. The actions (or "methods") on these objects are closely associated with the object itself.

http://en.wikipedia.org/wiki/Object-oriented_programming

This separation of concerns, along with other features of Object Orientation such as polymorphism, inheritance, message passing, decoupling and encapsulation, provide a logical and conceptual framework by which the complexity of large programs can be managed in a highly effective way.


答:
Sounds like you are describing a multi-tenant application.

A multi-tenant application is an application that has the same code but works on different data according to the clients logged on.

Here's an article on msdn describing this in-depth: http://msdn.microsoft.com/en-us/library/aa479086.aspx

Don't mind the references to MS technology, the principles work on most major RDBM systems.

Title: Does there exist a design-pattern for this problem?

Body:
I have a big database of data which we can consider today's system. The data has a web front-end which allows my users to update the data. Let's call this "original solution"

When new users come in they come as a set of new users. These users need their own data and their own web front-end. Let's call this a "solution". Originally we have 1 solution (the original solution), however I now need the same solution for a different set of users.

Some factors that need to be considered in the design:

The original solution may choose to implement other solutions updates and inserts on the data.

Any solution may choose to receive updated and inserted data from the original solution.

Updates between solutions should be easily shareable.

Now the easiest solution would be just to replicate the entire database and have some sort of process to write and read data between solutions. This however has a really high overhead when it comes to duplicate data, storage needs and so on. I would imagine storing some kind of delta between the data would be better?

I imagine a possible solution would be to design the architecture much like a source code control system with branches would be? When a new solution is implemented we branch the original solution. The different updates in branches can easily be updated into the main branch and vice-versa.

Is there any tips in how I can easily clone the data in the original solution to a new solution without replicating the actual database? Perhaps a design pattern I can use in the implementation?


答:
Having more code in the test for a given function is a sign that the function/method doesn't stick to the single responsibility principle.

This means that in time the code becomes more convoluted and the tests need to grow in size exponentially to accommodate all the code paths and possible parameter combinations.

Most anti-patterns out there violate the single responsibility principle so it's the first thing that goes out the window in a typical project. This leads to the situation that you mentioned.

A solution to this is to write concise tests for a given routine before writing the routine. If the tests are too complicated it means it's time for refactoring.


答:
I worked in a Java project in which we had more than 90% code coverage. The code of the unit tests was definitely more than the code of the project (I would reckon about 20 % more).

On the other hand we had very few bugs.


答: SQL Audit could definitely catch the changes but the audit events can be a little cryptic.  LOGbinder SQL translates them into readable English.  I think the Audit Action Group you'd want to enable is SCHEMA_OBJECT_CHANGE_GROUP</p>


问:
Are all programming problems algorithm problems?
I like how "Introduction to Algorithms" by Cormen et al. conveys knowledge. One reason is that everything has to do with programming problems and the book is not implemented in any particular programming language. This language independency provides focus on the ideas in general.

So my question is, as it says in the title. Is every solveable programming problem solveable by thinking in this algorithmic fashion. No matter which language, field, etc ? If yes, give arguments, else, give arguments!

I have not implemeted many complex programs with GUI, AI, Graphics, etc ... But are these types of problems also a matter of thinking out good algorithms?

答:
What do you mean by programming problem?

According to Wikipedia:

Computer programming (often shortened to programming or coding) is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs.

which means that programming in general is inherently larger than translating algorithms through code.

To give you an example, a programming problem I have right now is that I have to deal with a legacy spaghetti source code by adding unit tests, then refactoring it. It also involves adding comments in the right places, normalize the capitalization of names, etc. It has nothing or few to do with algorithms.

In the same way, many developer's tasks are unrelated to algorithms. Example: internationalization. In the very same way, lots of applications (CRUD, for example) don't use algorithms too much in their source code (not talking about the underlying code of the framework).

Now, if you're assuming that in "programming problem", "programming" is the synonymous of translation of algorithms through code, then yes, logically any problem would be an algorithm problem: A × n = B × n if A = B.


答:
It depends on how you define "Programming Problem".

In real-world projects, the answer is definitely a clear NO. Most of the problems are not even technical problems, but communication problems, requirements that are unclear, etc.

Then you have whole subjects of problem-classes that require next to no algorithms. For example, GUIs are often straightforward to "program", but the actual problem involved is to have a good design (from a useability point of view, not just the graphical appearance).

There are some fields, where the problems tend to be much more algorithmic by the nature of that field though. For example, AI is a prime subject, where algorithms are at the core. Graphics can be algorithm intensive, but it depends on what exactly is meant with "Graphics Programming".

In general, if the problem you are solving programmatically is suitable for a mathematical representation, then you are entering the algorithmic area. Of course, this is just a rough indicator, as you may create mathematical models for pretty much everything. But for most things you wouldn't normally consider doing so.

Final example: If the problem is to create a GUI that allows entering data for business objects, you wouldn't think about mathematical formulations much. If, however, the problem is to create a GUI that is dynamically changing and relocates elements based on some importance value, you are much more likely to end up with a mathematical model and an algorithmic implementation.

Title: Are all programming problems algorithm problems?

Body:
I like how "Introduction to Algorithms" by Cormen et al. conveys knowledge. One reason is that everything has to do with programming problems and the book is not implemented in any particular programming language. This language independency provides focus on the ideas in general.

So my question is, as it says in the title. Is every solveable programming problem solveable by thinking in this algorithmic fashion. No matter which language, field, etc ? If yes, give arguments, else, give arguments!

I have not implemeted many complex programs with GUI, AI, Graphics, etc ... But are these types of problems also a matter of thinking out good algorithms?


问:
Which approach to follow for developing applications targeting multiple platforms?
For applications targeting multiple platforms, I see mainly two development approaches-

Go for some JAVA-like development platform. Have one code solution and let the intermediate runtime handle different platforms. If something goes wrong in any platform, tweak the code a bit. But keep it same for all.

Make modular code separating core logic and UI. Develop separate UIs for respective platforms which will be calling same core libraries. Build the application separately for each of the target platforms.

So, which one to follow? I know, the answer will start with "It depends". But I want to hear your opinions on these approaches and the factors to be considered to choose any of them.

答: I've had pretty good luck with Mono.  I can write the same code for windows machines as I do for Linux machines, and for the most part, it works on both.  And I can use the skills I already know in C# and Winforms.</p>