答:
My main objection to this method of assessment is that it can be an obstacle to co-operation between developers. I think that an important part of the productivity of a development team is the willingness of team members to help each other. As I understand the suggested scheme, it could lead to developers sticking with their own assigned tasks and ignoring other team members who are stuck and could easily be unstuck by a little assistance.

We are always looking for the contribution the programmer is making to the team and the business.

Title: Is it right to appraise Scrum members according to number of successful user stories completed?

Body:
When my Manager told to team that "from now on successful user stories will be considered for appraisal!"

We sat there for while shocked and that was one of the several jaw dropping moments he gave us.

We felt that was stupid idea, since this will ruin all concept and goal of agile development methodology.

Let me know what you people think? And how can we convince him?


问:
How important are UML diagrams for a successful project?
I'm in the middle of a project and I was asked to write UML diagrams (use cases,class diagram,etc). The project isn't very complex.

I was wondering if this be a waste of my time? Should I just be doing other fun stuff like writing code? And when is it not ok to build something without going through all of the conceptual phase? Is it all about complexity? And if so, how to measure it?

答:
I have some thoughts about this. Language can be used and abused, compel and distract, trigger and lull. UML is just another language suited for a specific set of problems and just as any other language, it'll take time and effort to learn to speak it fluently and understand it correctly.

The decision on what to communicate is incredibly more important than the language it is communicated in. UML will not magically make your bad designs understandable. Just like any other language, it is easy to get lost in details or leave too much to the imagination.

UML got a bad name because of the numerous horrible IDE's, allowing round-trip prototyping, click-intensive graph manipulation and the difficulty of changing anything. UML 2.0 might be complex enough to satisfy certain academics, but its meta-model does not seem to attract many practical applications.

Still, I use UML from time to time. To evaluate a high-level design (a good design has complexity on the fringes and simplicity in the centre). To communicate an idea to a colleague and receive feedback. To find hidden relations, normalize, etc. But it's always a reflection of something that's already in my head. Generally, I draw UML with pen and paper, preferably away from any computer. If necessary, when a design crystallizes, I make a visual representation in a drawing program.

ContentLicense: CC BY-SA 3.0


问:
How to Mentor a Junior Developer
This title is a little broad but I may need to give a little background before I can ask my question properly.

I know that similar questions have been asked here already. But in my case I'm not asking if I should be mentoring someone or if the person is a good fit for being a software developer. That is not my place to judge. I have not been asked outright, but it is apparent that myself and other fellow senior developers are to mentor the new developers that start here. I have no problem with this whatsoever and, in many cases, it lends me a fresh perspective on things and I end up learning in the process. Also, I remember how beneficial it was in the beginning of my career when someone would take some time to teach me something.

When I say "new developer" they could be anywhere from fresh out of college to having a year or two of experience.

Recently we've had people start here who seem to have an attitude toward development/programming which is different from my own and hard for me to reconcile; they extract just enough information to get the task done but not really learn from it. I find myself going over and over the same issues with them. I understand that part of this could be a personality thing, but I feel it's my job to do my best and push them out of the nest while they're under my wing, so to speak.

How can I impart just enough information so that they will learn but not give so much as to solve the problem for them?

Or perhaps:

What's the proper response to questions that are designed to take the path of least resistance and, in essence, force them to learn instead of take the easy way out?

These questions are probably more general teaching questions and don't have that much to do specifically with software development.

Note: I do not get a say in what tasks they are working on. Management doles the task out and it could be anything from a very simple bug fix to starting an entire application by themselves. While this is not ideal by any means and obviously presents its own gauntlet of challenges, I feel it's a topic best left for another question. So the best I can do is help them with the problem at hand and try to help them break it down into simpler problems and also check their commit logs and point out mistakes that they made.

My main objectives are to:

Help them out and give them the tools they need to start becoming more self-reliant.

Steer them in the right direction and break bad development habits early on.

Lessen the amount of time I spend with them (the personality type described above tends to need much more one-on-one time and does not do well over IM or email. While that's generally fine, I can't always stop what I'm working on, break my stride, and help them debug an error on a moments notice; I have my own projects that need to get done).

答:
A thing to watch out for, for those getting excited at the prospect of doing all this mentoring for junior developers: make sure your management understands what's going on.

Teaching other people is hard work, in general. It takes focus and concentration, planning and effort, and most of all it takes time. Whatever approach you take, if you're teaching and mentoring in any serious fashion it's going to be eating into your time.

If your management hires less-experienced developers with the expectation that senior developers will take on training duties, make sure that's explicit. Find out what the time frame will be and make sure that your development schedules reflect the time and effort spent on training. Make sure management has some plans for evaluating the success of the mentoring efforts at some agreed-upon time(s). (Of course, if they're hiring developers that need teaching and mentoring, but management is not planning for it, then that's obviously a serious problem.)

Not everybody is a good teacher or mentor, and not everybody wants to be.  I don't mean to sound crusty or bitter; I like teaching, a lot. But it's silly to expect that everybody's going to be good at it (despite their own talents), nor can we expect everyone to enjoy the process (remember, it's not easy). Furthermore, if you're a senior developer who does not enjoy mentoring, or if you really feel you're a poor choice for a teacher or mentor, make sure your management understands that a plan involving you doing those duties is a plan with a serious flaw. On the other hand, if you want to become good at teaching or mentoring, that's something to communicate as well.

If teaching and mentoring are burdens shared unevenly across the population of senior developers, make sure that those assignments are recognized as valuable to the company in the same way that product development achievements are recognized.

Title: How to Mentor a Junior Developer


问:
Is Debug.Assert obsolete if you write unit tests?
Just like the question asks, is there a need to add Debug.Assert into your code if you are writing unit tests (which has its own assertions)? I could see that this might make the code more obvious without having to go into the tests, however it just seems that you might end up with duplicated asserts. It seems to me that Debug.Assert was helpful before unit-testing became more prevalent, but is now unnecessary. Or, am I not thinking of some use case?

答:
Assertions make assumptions explicit. Well-written unit tests do the same, but in an entirely different place.

Therefore, assertions, interspersed into the logic, help document the code and make it more understandable. This is how I use assertions. This is helpful in particular when implementing algorithms from theoretical descriptions, which usually offer the assertions as part of a correctness proof.

In a way, unit tests and assertions are two sides of the same coin: unit tests attempt to ensure correctness by trial, while assertions attempt to ensure it by proof.

Furthermore, assertions may help debug such algorithms because they offer sub-unit resolution, if you will. Unit tests on the other hand are inherently constrained to a coarser resolution. They can’t tell you anything about the internal state of an algorithm. Having small units helps but isn’t always feasible.


答:
UML has value if team members collectively understand it and consider it a useful way of summarising and communicating design decisions.  You don't need to know it all, just that subset that the team finds useful.

Also, you don't need to draw perfect, polished diagrams.  A roughly-sketched sequence diagram on a whiteboard or a class diagram in which classes are post-it notes stuck to that whiteboard might be sufficient, depending on the context.

Title: How important are UML diagrams for a successful project?

Body:
I'm in the middle of a project and I was asked to write UML diagrams (use cases,class diagram,etc). The project isn't very complex.

I was wondering if this be a waste of my time? Should I just be doing other fun stuff like writing code? And when is it not ok to build something without going through all of the conceptual phase? Is it all about complexity? And if so, how to measure it?


答:
Unit tests assert correctness for specific inputs (the test inputs).

Contract assertions (or debug assertions) assert correctness for any given input.

If you want your code to be safer then the combination between the two will produce better results.

Title: Is Debug.Assert obsolete if you write unit tests?

Body: Just like the question asks, is there a need to add Debug.Assert into your code if you are writing unit tests (which has its own assertions)? I could see that this might make the code more obvious without having to go into the tests, however it just seems that you might end up with duplicated asserts. It seems to me that Debug.Assert was helpful before unit-testing became more prevalent, but is now unnecessary. Or, am I not thinking of some use case?


答:
As others have already mentioned, a combination of assertions and unit tests will document your code better and help to ensure correctness, but they are used for different reasons: assertions verify the internal state of a codebase while unit tests verify the external behavior of a codebase.

Also keep in mind that assertions and unit tests can be executed separately as well as together. Here are a few scenarios:

Building the code in the IDE and running it in Debug configuration will only execute assertions.

Executing unit tests in Debug configuration will also execute assertions.

Executing unit tests in Release configuration will not execute assertions.

Therefore, it helps to have assertions scattered throughout the codebase that will be executed in Debug configuration as well as unit tests that can be executed separately in either Debug or Release configuration.


答: I find them highly overrated. I consider them the only pictures that don't paint a thousand words.</p>


答:
UML is only of value if the people designing the system cannot write the code themselves. ie, UML is a 'language' that communicates the architectural concepts to someone else, now if you're the person who is designing the code and implementing it, then why would you need to show yourself what it is you're going to do?! Get on and head straight for the coding instead. You'll still have to document what you did later, but the overall efficiency is quicker.

But, if you were a system architect wanting to tell your outsourced team of developers what you wanted, then you'd have to tell them somehow, and that's where UML comes in. However, I think that there are plenty of alternative means of performing this task nowadays, and frankly, the complexity of the UML diagramming means everyone has to understand how to read it, which is somewhat self-defeating if they don't.


问:
Should I care about Junit redundancy when using setUp() with @Before annotation?
Even though developers have switched from junit 3.x to 4.x I still see the
following 99% of the time:

```<code>@Before
public void setUp(){/*some setup code*/}

@After
public void tearDown(){/*some clean up code*/}
</code>```

Just to clarify my point... in Junit 4.x, when the runners are set up correctly, the framework will pick up the @Before and @After annotations no matter the method name. So why do developers keep using the same conventional junit 3.x names? Is there any harm keeping the old names while also using the annotations (other than it makes me feel like devs do not know how this really works and just in case, use the same name AND annotate as well)?

Is there any harm in changing the names to something maybe more meaningful, like
eachTestMethod() (which looks great with @Before since it reads 'before each test method') or initializeEachTestMethod()?

What do you do and why?

I know this is a tiny thing (and may probably be even unimportant to some), but it is always in the back of my mind when I write a test and see this. I want to either follow this pattern or not but I want to know why I am doing it and not just because 99% of my fellow developers do it as well.

答:
I do use setUp() when I can't think of a better name.  Part of the problem is that the setUp method has a variety of things in it so another name doesn't present itself.

There is a problem with using setUp for all the methods.  You have to remember to call the superclass setUp if it exists.  Unlike in JUnit 3.8 where you could just do so all the time.

When I am writing an abstract test I make an effort to use a name that is not setUp() to avoid putting this burden on the subclass implementers.  Granted it is pretty obvious there is a problem due to the NullPointer.  But writing a test superclass is like writing reusable code.  You want to make things easy for the callers!


问:
Is continuous integration useful for a team of two developers who write a lot of code?

Possible Duplicate:

  How many developers before continuous integration becomes effective for us?

I'm new with continous integration though I have used it without know the term. So, I'm interested about the mechanism can be possible to implement and my question is: can a continuous integration server be useful for a team of two developers? (but that write a lot of code)

答:
Its probably better for a team that writes a lot of code. It allows you to worry about writing code, leaving the CI server to automatically run release builds, check dependancies and some static analysis - if you're doing your job right, it'll be silently compiling your checkins. If you're getting things wrong, it'll email you what errors it's finding. </p>

<p>If you get a lot of emails from it, then its obvious you're not working together very well, the emails will tell you what areas you need to look into, whether that's because you're writing poor code, or checking in code that breaks the other's code. </p>

Body:
Its probably better for a team that writes a lot of code. It allows you to worry about writing code, leaving the CI server to automatically run release builds, check dependancies and some static analysis - if you're doing your job right, it'll be silently compiling your checkins. If you're getting things wrong, it'll email you what errors it's finding.

If you get a lot of emails from it, then its obvious you're not working together very well, the emails will tell you what areas you need to look into, whether that's because you're writing poor code, or checking in code that breaks the other's code.


答:
If someone asked you to prepare UML diagrams and that someone is paying your salary, then it is not really a waste of your time.  It may or may not be a waste of that someone's time.

If that someone is planning to understand your project by reading your UML diagrams, then it probably is not a waste of their time.


答:
I would recommend start giving parts of real assignments you have and make everything to be able to use his code. In other words train him as replacement for yourself.

This way you will commit yourself to allocating time to work with junior and he will be able to see "real life". By working on real assignments and hearing lively feedback he will be able to get p to speed rather quickly.

Title: How to Mentor a Junior Developer

Body:
This title is a little broad but I may need to give a little background before I can ask my question properly.

I know that similar questions have been asked here already. But in my case I'm not asking if I should be mentoring someone or if the person is a good fit for being a software developer. That is not my place to judge. I have not been asked outright, but it is apparent that myself and other fellow senior developers are to mentor the new developers that start here. I have no problem with this whatsoever and, in many cases, it lends me a fresh perspective on things and I end up learning in the process. Also, I remember how beneficial it was in the beginning of my career when someone would take some time to teach me something.

When I say "new developer" they could be anywhere from fresh out of college to having a year or two of experience.

Recently we've had people start here who seem to have an attitude toward development/programming which is different from my own and hard for me to reconcile; they extract just enough information to get the task done but not really learn from it. I find myself going over and over the same issues with them. I understand that part of this could be a personality thing, but I feel it's my job to do my best and push them out of the nest while they're under my wing, so to speak.

How can I impart just enough information so that they will learn but not give so much as to solve the problem for them?

Or perhaps:

What's the proper response to questions that are designed to take the path of least resistance and, in essence, force them to learn instead of take the easy way out?

These questions are probably more general teaching questions and don't have that much to do specifically with software development.

Note: I do not get a say in what tasks they are working on. Management doles the task out and it could be anything from a very simple bug fix to starting an entire application by themselves. While this is not ideal by any means and obviously presents its own gauntlet of challenges, I feel it's a topic best left for another question. So the best I can do is help them with the problem at hand and try to help them break it down into simpler problems and also check their commit logs and point out mistakes that they made.

My main objectives are to:

Help them out and give them the tools they need to start becoming more self-reliant.

Steer them in the right direction and break bad development habits early on.

Lessen the amount of time I spend with them (the personality type described above tends to need much more one-on-one time and does not do well over IM or email. While that's generally fine, I can't always stop what I'm working on, break my stride, and help them debug an error on a moments notice; I have my own projects that need to get done).


问:
Are there currently any modern, standardized, aptitude test for software engineering?

Background

I am a working software engineer who is in the midst of seeking out a new contract for the next year or so.  In my search, I am enduring several absurd technical interviews as indicated by this popular question I asked earlier today.

Even if the questions I was being asked weren't almost always absurd, I would be tired nonetheless of answering them many times over for various contract opportunities.

So this got me thinking that having a standardized exam that working software professionals could take would provide a common scorecard that could be referenced by interviewers in lieu of absurd technical interview questions (i.e. nerd hazing).

Question

Is there a standardized software engineering aptitude test (SEAT??) available for working professionals to take?

If there isn't a such an exam out there, what questions or topics should be covered?

An additional thought

Please keep in mind, if suggesting a question or topic, to focus on questions or topics that would be relevant to contemporary development practices and realistic needs in the workforce as that would be the point of a standard aptitude test.  In other words, no clown traversal questions.

答: The Language-Free Programmer/Analyst Aptitude Test provides an objective measure of a job candidate's potential to understand and apply reasoning, logic, computer math, and procedural rules. The LPAT does not test the candidate in a specific computer language. See http://www.aprtestingservices.com/business/lpat/</p>


答:
I was never a fan of UML, but I have come to value a good sequence diagram to describe interactions between systems or tasks.

However the class diagram is obsolete before it is born. A rough design does not require UML, and a thorough documentation is better automatically extracted (live) from the code base. Javadoc and Doxygen have completely obsoleted the need for manual class diagrams.

The thing about documentation is that there are two levels:

high level (architectural) decisions should be documentation manually

low level (entities relationships) facts should be extracted automatically


问:
How important is it for a programmer to have an online presence?
I've noticed more and more mentions (both in posts here and in actual job descriptions) of programmers' "portfolios" - typically their public profiles on sites such as this, GitHub, etc.

How important is this, and would companies (startups in particular) reject (or immediately discard without even interviewing) otherwise outstanding candidates who don't have an online presence?

Personally, I prefer to keep a very low profile online. My name here cannot identify me, and I have other handles for other sites. I have a very spartan (and completely private) Facebook page. I do code on my own, but the code lives in local repositories. In general, the less information online about me, the better.

I could see a designer needing some sort of online portfolio, but for a programmer, is this really a big negative when job-searching?

答: I was recently asked by a startup company to give the online references to showcase my work and the technical prsence, I suppose the domain matters a lot, If you look for a job in Android/iOS/games and web apps related jobs then be prepared to show your work. If you are into embedded/financial/banking/DB looking for a job in larger firms then the track record matters more. </p>


问:
Is it right to appraise Scrum members according to number of successful user stories completed?
When my Manager told to team that "from now on successful user stories will be considered for appraisal!"

We sat there for while shocked and that was one of the several jaw dropping moments he gave us.

We felt that was stupid idea, since this will ruin all concept and goal of agile development methodology.

Let me know what you people think? And how can we convince him?

答:
Sandy, unfortunately your manager's statement is a classic misunderstanding of scrum in particular and agile in general.

The proposed approach kills collaboration and counters the principle of collective code ownership.  User stories in agile (if it is a real agile) rarely get completed before being touched by multiple people.  Also, you will have user stories from time to time that need swarming in order to be finished within the iteration.  How are you going to all get that when the individual incentives are aligned 180 degrees in the opposite direction?

Your teams instincts are correct.  What sources would I suggest in the short term for you to read as you brainstorm the response to your manager?  Look at blogs of renowned agile experts like Mike Cohn, Martin Fowler, Elizabeth Hendrickson, Jurgen Appelo, Esther Derby and several others and look for articles about agile team organization.

ContentLicense: CC BY-SA 4.0


问:
force recompilation of war file including its Jar dependencies
I have a project A (a webapp), depending on project B (B.jar) and this one depending on project C (C.jar).

I would like to create a maven goal named "Rebuild War", that clean all compiled code for these 3 projects and rebuild the whole in order to obtain a fresh War file.

I tried mvn clean package on project A, but I noticed that B and C are not recompiled. Indeed,  B.jar and C.jar that are contained in local repository don't have a changing creation date.

Is there an adapted maven command for this requirement ?

答:
Given a directory structure of

```<code>/foo/A/pom.xml
/foo/B/pom.xml
/foo/C/pom.xml
</code>```

you need to introduce

```<code>/foo/pom.xml
</code>```

and that should specify A, B and C as modules.  You can now do cd /foo; mvn clean install and have A, B, and C recompiled.  If your dependencies are correct, they even do so in the correct order.

Body:
Given a directory structure of

/foo/A/pom.xml
/foo/B/pom.xml
/foo/C/pom.xml

you need to introduce

/foo/pom.xml

and that should specify A, B and C as modules.  You can now do cd /foo; mvn clean install and have A, B, and C recompiled.  If your dependencies are correct, they even do so in the correct order.


问:
Formalizing programmers errors
Every one of us make errors leading to bugs. Once I wanted to start logging my errors for future analysis, probably mentioning project title, approximate time spent and the most important, the type of error. For example when I copy-pasted a fragment about 'x' and replaced every occurrence of 'x' with 'y' and forgot to replace a tiny piece, this goes to 'copy-paste error'. The usefulness of this approach depends on whether I can formalize my errors at all and probably minimizing the number of types to choose from. Otherwise I would start postponing, ignoring and so on so make this system useless.

Are there existing research in this area, probably a known minimum set of errors? Maybe some of you already tried to implement something like this and succeeded/failed?

答:
Take a look at Brain Hayes' Debugging Myself.  I'm not sure that he started out with error categories, or just determined them as time goes on.

I think this is an inherently difficult area.  What do you classify as an error? I personally wouldn't classify a typo as an error, but if you're doing Personal Software Process, I'm pretty sure that you do classify misspelled key words as an error.

Title: Formalizing programmers errors


答:
What you're looking for is a taxonomy of software bugs. Here are several of such taxonomies:

http://cs.nyu.edu/~lharris/content/bugtaxonomy.html

http://spin.atomicobject.com/2011/05/01/taxonomy-of-software-bugs/

http://www.mcr.org.in/sureshmudunuri/stm/unit1.php#bug_taxonomy

Here's even a thesis paper of someone who surveyed 26 different bug taxonomies.

You'll probably find that each taxonomy is a little different, with different categories, different levels of detail, and even completely different basic concepts.

I wouldn't worry too much about what categories to choose exactly, or what category to assign individual bugs too. It seems like a rather useless exercise in futility to aim for a perfect categorization of something as varied as software bugs.

Title: Formalizing programmers errors

Body:
Every one of us make errors leading to bugs. Once I wanted to start logging my errors for future analysis, probably mentioning project title, approximate time spent and the most important, the type of error. For example when I copy-pasted a fragment about 'x' and replaced every occurrence of 'x' with 'y' and forgot to replace a tiny piece, this goes to 'copy-paste error'. The usefulness of this approach depends on whether I can formalize my errors at all and probably minimizing the number of types to choose from. Otherwise I would start postponing, ignoring and so on so make this system useless.

Are there existing research in this area, probably a known minimum set of errors? Maybe some of you already tried to implement something like this and succeeded/failed?


问:
Should all public methods in an abstract class be marked virtual?
I recently had to update an abstract base class on some OSS that I was using so that it was more testable by making them virtual (I could not use an interface as it combined two). This got me thinking whether I should mark all of the methods that I needed virtual, or if I should mark every public method/property virtual. I generally agree with Roy Osherove that every method should be made virtual, but I came across this article that got me thinking about whether this was necessary or not. I am going to limit this down to abstract classes for simplicity, however (whether all concrete public methods should be virtual is especially debatable, I am sure).

I could see where you might want to allow a sub-class to use a method, but not want it overriding the implementation. However, as long as you trust that Liskov's Substitution Principle will be followed, then why would you not allow it to be overriden? By marking it abstract, you are forcing a certain override anyway, so, it seems to me that all public methods inside of an abstract class should indeed be marked virtual.

However, I wanted to ask in case there was something I might not be thinking. Should all public methods within an abstract class be made virtual?

答:
Ask yourself what the use is of a non-virtual method in an abstract class. Such a method would have to have an implementation to make it useful. But if the class has an implementation, can it still be called an abstract class? Even if the language/compiler allows it, does it make sense? Personally, I don't think so. You would have a normal class with abstract methods that descendants are expected to implement.

My primary language is Delphi, not C#. In Delphi, if you mark a method abstract, you also have to mark it virtual or the compiler complains. Haven't followed the latest language changes too closely, but if abstract classes are in or would come to Delphi, I would expect the compiler to complain about any non-virtual methods, any private methods and about any method implementations for a class marked abstract at the class level.


答:
I once worked on a gig where I needed to manage a team of contract developers overseas.

Some of the stuff they were producing was pretty horrendous (a common symptom of remote contract coders - they don't really care a lot for your code, they just want to get done fast).

To manage the project, I found myself producing UML diagrams and handing it to them to code. It was very successful - it didn't take me that long to write a program in UML, much faster than in Java, and it was something the contractors could follow and be measured against.

One caveat - they did at times want to become creative and deviate from my models, however in those cases they were actually correct, and over all the UML improved the quality of the final product


问:
how a pure functional programming language manage without assignment statements?
When reading the famous SICP, I found the authors seem rather reluctant to introduce the assignment statement to Scheme in Chapter 3. I read the text and kind of understand why they feel so.

As Scheme is the first functional programming language I ever know something about, I am kind of surprised that there are some functional programming languages (not Scheme of course) can do without assignments.

Let use the example the book offers,the bank account example. If there is no assignment statement, how can this be done?How to change the balance variable? I ask so because I know there are some so-called pure functional languages out there and according to the Turing complete theory, this must can be done too.

I learned C, Java, Python and use assignments a lot in every program I wrote. So it's really an eye-opening experience. I really hope someone can briefly explain how assignments are avoided in those functional programming languages and what profound impact (if any) it has on these languages.

The example mentioned above is here:

```<code>(define (make-withdraw balance)
    (lambda (amount)
        (if (>= balance amount)
            (begin (set! balance (- balance amount))
                balance)
            "Insufficient funds")))
</code>```

This changed the balance by set!. To me it looks a lot like a class method to change the class member balance.

As I said, I am not familiar with functional programming languages, so if I said something wrong about them, feel free to point out.

答:
In a purely functional language, one would program a bank account object as a stream transformer function.  The object is regarded as a function from an infinite stream of requests from the account owners (or whoever) to a potentially infinite stream of responses.  The function starts off with an initial balance, and processes each request in the input stream to calculate a new balance, which is then fed back to the recursive call to process the remainder of the stream.  (I recall that SICP discusses stream-transformer paradigm in another part of the book.)

A more elaborate version of this paradigm is called "functional reactive programming" discussed here on StackOverflow.

The naive way of doing stream transformers has some problems.  It is possible (in fact, pretty easy) to write buggy programs that keep all the old requests around, wasting space.  More seriously, it is possible to make the response to the current request depend on future requests.  Solutions to these problems are currently being worked on.  Neel Krishnaswami is the force behind them.

Disclaimer: I do not belong to the church of pure functional programming.  In fact, I do not belong to any church :-)


问:
Is it a bad decision to release code that is not open source
I work for a company that owns several closed source software. One of our software is used to service clients and generate income so it has commercial value to us (and it pays my salary).

I've talked about open sourcing the code, but the option of open sourcing under something like the MIT or GPL or any other open source license that allows competitors to install it and offer it to our clients for cheaper has met clear resistance.

What about showing the code but not under an open source license?

The arguments I've been getting against this is that this move will confuse clients and developers and will get us more bad publicity than any good thing. The developer of PAINT.NET used to release his code and got a lot of flack when he started reminding competitors that the code is only for educational purposes and isn't really open source.

I've also been told that open sourcing for the sake of open sourcing doesn't make sense, bla bla bla, and that unless I have a plan for how that's going to bring more revenue, it's not for us. Well, honestly I don't have a plan, but I thought why not try. Of course I can't say if this will help us or hurt us. I don't want to take the responsibility for a move that might hurt a company that's doing well and get people laid off.

As I said, an open source license does not look like an option, so it's between closed source or showing the code but still under a normal copyright license. But as I said there's resistance to showing the code because of the worry that competitors will use our code to create their own.

Does anyone know of any facts that can help with this decision, whether in favor or against showing the code.

答:
In a comment you mention when asked for a reason to open source you replied "Obviously I'm hoping it will benefit the company somehow, but as I said, I don't know yet exactly how."

That's not a good enough reason.  You absolutely must know how it benefits the company.  It's not a try it and see how it turns out kind of decision.

Like @Vatine said there are many companies that will license the source in addition to the software, sometimes for an additional price.  It gives a little peace of mind in that if there's a critical bug affects their customer they can make a hot-fix while they wait for your company to fix it.

The other big benefit of open-source is the community.  As @Konrad says, if the source is available but not open it greatly diminishes this effect. Also a community doesn't just establish itself, it needs promoting which costs time and/or money.

Also think about what actually makes the money for your company.  Is it the software itself, or is it something external and the software is merely a facilitator?  Google makes most of their money through advertisement.  The fact they open source most of their software and is a huge proponent of open source isn't negatively impacted by having the source out there.  It's the user-base that is their biggest asset, not the software.  Open-sourcing helps build that user-base and build good-will.

Does your company have a model that would benefit from a large non-paying user-base?  By non-paying I mean paying for the software.  If you're selling the software directly you can more or less forget it.  If you're providing support or consultation services then you can use open source to give you an edge over the competition.  Open sourcing then can help build brand recognition.  Notice I said "can" and not "will".  It still needs to be marketed and promoted properly otherwise it's useless.  It's all about building a community.

In addition to the above, it's also a very personal decision for the company.  Is the personality of the company an open culture?  If it's not fully embraced by the company, especially at the head, it's not going to work.  Once it goes open source you can't just close it.  You can close future modifications, but what's out there will be out there, you can't take it back, so it's not a willy-nilly decision.  You absolutely must know how and why it will benefit your company specifically.

OwnerDisplayName: samiii

ContentLicense: CC BY-SA 2.5


答: The Personal Software Process emphasizes a lot of these things.  Improving quality and estimation by keeping logs of the past/present.  I recommend looking at sample forms for ideas.</p>

Title: Formalizing programmers errors


答:
It's perfectly reasonable, and sometimes desirable to have non-virtual methods in an abstract base class;  just because it's an abstract class doesn't necessarily mean every part of it should be usable polymorphically.

For example, you might want to use the 'Non virtual polymorphism' idiom, whereby a function is called polymorphically from a non-virtual member function, in order to ensure that certain preconditions or postconditions are met before the virtual function is called

```<code>class MyAbstractBaseClass
{
protected:
    virtual void OverrideMe() = 0;
public:
    void CallMeFirst();

    void CallMe()
    {
        CallMeFirst();
        OverrideMe();
    }
};
</code>```

Title: Should all public methods in an abstract class be marked virtual?

Body:
I recently had to update an abstract base class on some OSS that I was using so that it was more testable by making them virtual (I could not use an interface as it combined two). This got me thinking whether I should mark all of the methods that I needed virtual, or if I should mark every public method/property virtual. I generally agree with Roy Osherove that every method should be made virtual, but I came across this article that got me thinking about whether this was necessary or not. I am going to limit this down to abstract classes for simplicity, however (whether all concrete public methods should be virtual is especially debatable, I am sure).

I could see where you might want to allow a sub-class to use a method, but not want it overriding the implementation. However, as long as you trust that Liskov's Substitution Principle will be followed, then why would you not allow it to be overriden? By marking it abstract, you are forcing a certain override anyway, so, it seems to me that all public methods inside of an abstract class should indeed be marked virtual.

However, I wanted to ask in case there was something I might not be thinking. Should all public methods within an abstract class be made virtual?

Body:
It's perfectly reasonable, and sometimes desirable to have non-virtual methods in an abstract base class;  just because it's an abstract class doesn't necessarily mean every part of it should be usable polymorphically.

For example, you might want to use the 'Non virtual polymorphism' idiom, whereby a function is called polymorphically from a non-virtual member function, in order to ensure that certain preconditions or postconditions are met before the virtual function is called

class MyAbstractBaseClass
{
protected:
    virtual void OverrideMe() = 0;
public:
    void CallMeFirst();

    void CallMe()
    {
        CallMeFirst();
        OverrideMe();
    }
};


问:
What do you do to improve your logical programming skills?
Do you think that only the programming pratice will help you to improve your logical programming skill or do you train your brain with puzzle games, trying imagine how universe works, playing instruments and so on?

Devoting more time with programming, will do you get logical programming skills more fast?

答:
I've found that, through learning about programming and software development (not necessarily formally), I've learned to break down problems in to smaller and smaller chunks more effectively.

I think you can improve that particular skill by using it outside of the software development field; by trying to break down problems you come across in everyday life. Trying to understand how something new works (like an engine or a piece of electronics) using this technique is particularly good.


问:
How could RDBMSes be considered a fad?
Completing my Computing A-level in 2003 and getting a degree in Computing in 2007, and learning my trade in a company with a lot of SQL usage, I was brought up on the idea of Relational Databases being used for storage.

So, despite being relatively new to development, I was taken-aback to read a comment (on https://softwareengineering.stackexchange.com/q/89994/12436 ) that said:

[Some devs] despise [SQL] and think that it and RDBMS are a fad

Obviously, a competent dev will use the right tool for the right job and won't create a relational database when e.g. flat file or another solution for storage is appropriate, but RDBMs are useful in a massive number of circumstances, so how could they be considered a fad?

答:
The Wiki Def. of Fad, defines the term "fad" as follows:
A fad is any form of behavior that develops among a large population and is collectively followed with enthusiasm for some period, generally as a result of the behavior's being perceived as novel in some way. A fad is said to "catch on" when the number of people adopting it begins to increase rapidly. The behavior will normally fade quickly once the perception of novelty is gone.

Since RDBMS followers did not fade quickly, and is not about to go away in many years to come (thanks to the huge pile of production applications using it) we can't say that its a fad. In fact the core concepts of RDBMS remained fairly stable where so many of the other technologies changed (and still are changing) dramatically.

The concept of RDBMS (and its main vehicle, SQL) represent a step in technology that, like many others, may be superseded by better ones, that is all.

Title: How could RDBMSes be considered a fad?


答:
However, as long as you trust that Liskov's Substitution Principle will be followed, then >why would you not allow it to be overriden?

You don't make certain methods virtual because you don't believe this to be the case. Further, by making certain methods not virtual, you're signaling to inheritors what method(s) should be implemented.

Personally, I will often make method overloads that exist for convenience not virtual so that users of the class can have consistent defaults and implementers aren't even able to make the error of breaking that implied behavior.


答:
However, as long as you trust that Liskov's Substitution Principle will be followed, then why would you not allow it to be overriden?

For example, because I want the skeleton implementation of an algorithm to be fixed, and only allow specific parts to be (re)defined by subclasses. This is widely known as the Template Method pattern (emphasis below by me):

The template method thus manages the larger picture of task semantics, and more refined implementation details of selection and sequence of methods. This larger picture calls abstract and non-abstract methods for the task at hand. The non-abstract methods are completely controlled by the template method but the abstract methods, implemented in subclasses, provide the pattern's expressive power and degree of freedom. Some or all of the abstract methods can be specialized in a subclass, allowing the writer of the subclass to provide particular behavior with minimal modifications to the larger semantics. The template method (which is non-abstract) remains unchanged in this pattern, ensuring that the subordinate non-abstract methods and abstract methods are called in the originally-intended sequence.

Update

Some concrete examples of projects I have been working on:

communicating with a legacy mainframe system via various "screens". Each screen has a bunch of fields, of fixed name, position and length, containing specific data bits. A request fills up certain fields with specific data. A response returns data in one or more other fields. Each transaction follows the same basic logic, but the details are different on every screen. We used Template Method in several different projects to implement the fixed skeleton of the screen handling logic, while allowing subclasses to define the screen-specific details.

exporting / importing configuration data in DB tables to/from Excel files. Again, the basic schema of processing an Excel file and inserting/updating DB records, or dumping the records to Excel is the same for each table, but the details of each table are different. So Template Method is a very obvious choice to eliminate code duplications and make the code easier to understand and maintain.

Generating PDF documents. Each document has the same structure, but their content is different each time, depending on lots of factors. Again, Template Method makes it easy to separate the fixed skeleton of the generation algorithm from the case-specific, changeable details. In fact. it even applies on multiple levels here, as the document consists of several sections, each of which consists of zero or more fields. Template Method is applied on 3 distinct levels here.

In the first two cases, the original legacy implementation used Strategy, resulting in lots of duplicated code, which of course over the years grew subtle differences here and there, contained lots of duplicated or slightly different bugs, and was very difficult to maintain. Refactoring to Template Method (and some other enhancements, like using Java annotations) reduced code size by about 40-70%.

These are only the most recent examples which come to my mind. I could cite more cases from almost every project I have been working on so far.


问:
Are code reviews necessary for junior developers?
I've worked at two companies, who each had a different methodology when it came to code reviews:

In the first company, a code review was conducted by the team leaders and was required after the completion of every module.

However, in the second company, team leaders weren't required to conduct any code reviews, and just checked for functionality and design issues.

So I am confused. Is the code review process really needed? If it is, why? And if it isn't, why not?

答:
Code Review: The Code Review process must be a vital one for all, I will explain who are all get benefits due to conduction of code review as well as what are the benefits they are getting.

1. Benefits Obtained By the Company Due to the Conduction of Code Review:
        If frequent code review is conducted, then the company can get the final products in much better optimized way which help them to get branded name in their market and also help company to get or improve their current CMMI level.

2. Benefits to Team Leader Due to the Conduction of Code Review:
       As we all know a teacher can easily identify the mistakes, because they are reviewing the answers of their students more frequently, so they can get an idea , in which areas there may be possible for wrong things. similarly the team leader also knows what are the things goes wrong in this areas. How can we rectify those.And also Help the team Leader to grab the news ideas from the junior developer too.

3. Benefits to The Junior Developer  Due to the Conduction of Code Review:
       Junior Developer can easily grab the ideas about Code review Process, also they are able to get what is the coding standard, For Instance: to create API in a proper way, they will learn the standardization of the coding which may help them in future specially when they are become in Higher level post.

So My Conclusion is Code review is a Very Very Vital Process for all[even for team Member too], since code Reviewing helps us to correct our careless mistakes in our code,because we are all human beings, so we cannot predict that we never do careless mistakes in code.


问:
Importing an existing project into Git

Background

During the course of developing our site (ASP.NET), we discovered that our existing source control (SourceGear Vault) wasn't working for us. So, we decided to migrate to Git. The translation has been less than smooth though.

Our site is broken up into three environments DEV, QA, and PROD. For tho most part, DEV and the source control repo have been in sync with each other. There is one branch in the repo, if a page was going to be moved up to QA then the file was moved manually, same thing with stuff that was ready for PROD. So, our current QA and PROD environments do not correspond to any particular commit in the master branch.

Clarification: The QA and PROD branches are not currently, nor have they ever been in source control.

The Question

How do I move QA and PROD into Git? Should I forget about the history we've maintained up to this point and start over with a new repo? I could start with everything on PROD, then make a branch and pull in everything from QA, and then make another branch off of that with DEV. That way not only will the branches reflect the differences in the environments, they'll be in the right order chronologically with the newest commits in the DEV branch.

What I've tried so far

I thought about creating a QA branch off of the current master and using robocopy to make the working folder look like the current QA environment. This doesn't work because the new commit from QA will remove new files from DEV and that will remove them when we merge up, I suspect there will be similar problems if I started QA at an earlier (though not exact) commit from DEV.

答:
This won't solve your problem but perhaps it gives you an idea of how someone did it to svn: Any tool to migrate repo from Vault to Subversion?

Hope it helps!

Title: Importing an existing project into Git


问:
When is it acceptable to NOT fix broken windows?
In reference to broken windows, are there times when refactoring is best left for a future activity?

For example, if a project to add some new features to an existing internal system is assigned to a team that has not worked with the system until now, and is given a short timeline in which to work with - can it be ever be justifiable to defer major refactorings to existing code for the sake of making the deadline in this scenario?

答: If managers decide that they want to build up technical debt. This is a fair decision to make if one, for example, just want an early prototype out to some initial customers to get some early feedback.</p>


答:
Normally, when you are able to, you should fix it,  This will prevent potential time spent for maintenance.  However, some barbaric non-agile practice tends to let the status quo as it is as long as it is working.  Some managers are afraid of the "unforeseen effects" of the change.

My take is to leave it only if it is working as it should ( only broken by optimization but not functionality) and you lack the time to test it, if you do some refactoring.  However,  you should note that it should be fixed later as soon as possible.

If its broken by functionality and you new features depend on it, it would be best to fix it ASAP as well.

Title: When is it acceptable to NOT fix broken windows?

Body:
In reference to broken windows, are there times when refactoring is best left for a future activity?

For example, if a project to add some new features to an existing internal system is assigned to a team that has not worked with the system until now, and is given a short timeline in which to work with - can it be ever be justifiable to defer major refactorings to existing code for the sake of making the deadline in this scenario?


答:
Refactoring is - and should be - an ongoing process. It's not enough to simply meet requirements with a working and tested implementation that is still a little incomplete.

"Make it work, then make it work better".

I can't remember where I read that quote, but this is the key to applying refactoring well, and I count it as unprofessional to do otherwise.

Continuous refactoring is like wiping up the spills while you are cooking, and cleaning your dishes after you've eaten your meal. Targeted refactoring is like finding a dirty kitchen, but only having the time to wash a dirty glass or two. Would you rather live with a continuously dirty kitchen, or would you prefer to keep things clean as you go along?

You get the code to work, then you refactor your code to ensure that you have the best implementation you can possibly use.  If you're doing something familiar, it may be that you implement the best code first time, however it bears taking a moment to double-check your work to be sure. If it looks as though you could improve your code, then you try to refactor to make sure your code is at the very least as lean and clean as you can make it. This means you are reducing the amount of technical debt you leave behind, and you make it easier to read and refactor the next time the code needs to be dealt with. This is the core value behind the TDD mantra "Red-Green-Refactor", except that where in TDD you refactor primarily to remove duplication, it pays to also review other items that could be refactored, such as large classes, long methods, and other "code-smells" that can often contribute to technical debt.

If you find yourself facing a major redesign, then perhaps you can put it off for a while, particularly if you are running very low on time in your schedule. This is however provided the functionality of your code will not be compromised, and also provided the implementation will continue to meet the requirements. This sort of situation should be a rare occurrence, and you can help to ensure it is even rarer if you are continuously refactoring as you go along. Even more important however is that you can't risk leaving your major changes for too long, otherwise you will end up creating an even bigger workload later which could either be much more costly to fix, or could end up resulting in an even more costly project failure.

I get the impression that many people tend to confuse the definitions for Refactoring and Re-engineering. The two terms describe strategies to manage very different situations.  If you wish to re-engineer, you're making a commitment to make a drastic change which will alter the behaviour of a system. This will invalidate some tests, and will also require new tests. When you Refactor, you are ensuring you're system continues to behave exactly the same as it did before the change, however you are also ensuring that your code will have longevity, and that it will be easier to maintain over time. You're not "pimping" your code for the hell of it, you are committing to a professional standard of clean code that will reduce the risk of failure, and will ensure your code remains a pleasure to work with, and of a professional standard.

Going back to the broken windows analogy, if you break the window you should repair it right away.  If you haven't noticed that a window is broken, then you need to decide the cost to you if you leave the window broken. Now, repeat the previous two sentences, but substitute Bug for window. You end up needing a different strategy. If you have created a bug as you code, you fix it right away, or you see if the changes will require a re-engineering effort, and you make a commercial decision as to when it will be best to sort the problem out. So you don't refactor to fix a problem, you refactor to ensure it is easier to find and fix problems. I don't care how amazing you think your code is, complex systems will always have problems that will need to be dealt with over time. This is what technical debt is all about, and why refactoring needs to be an ongoing process as you implement your code, and not left for some arbitrary future time.

So in short, the answer that it may at rare times be acceptable to defer major changes to code in order to make a deadline, however it should not be considered normal practice to treat refactoring as an exercise independent of your daily implementation work, and certainly never used as an excuse by teams unfamiliar with the code base as an option to avoid ensuring that their implementation is as lean and clean as they can possibly make it under the circumstances.


问:
What is the preferred Internet media type of a RESTful POST request?
Is there a preferred/recommended Internet Media Type for RESTful POST requests?

For example, if I want to add a new user, should I send the data as a URL encoded string like:

```<code>name=Foo&otherData=Bar
</code>```

or does REST recommend I send the data as whatever format the response is going to be sent as (e.g. JSON/XML)?

```<code><user>
  <name>Foo</name>
  <other-data>Bar</other-data>
</user>
</code>```

答: If you can choose, use JSON. It's simple, readable, easily handled both in the server, client or browser's JavaScript, and quick to parse. And is in effect the informal standard for REST. Although XML is usually supported too by most frameworks, there's no reason to use it unless you're somehow forced to. But a URL-like string is definitely not a normal encoding for POST data in REST.</p>


问:
Do I suffer from encapsulation overuse?
I have noticed something in my code in various projects that seems like code smell to me and something bad to do, but I can't deal with it.

While trying to write "clean code" I tend to over-use private methods in order to make my code easier to read. The problem is that the code is indeed cleaner but it's also more difficult to test (yeah I know I can test private methods...) and in general it seems a bad habit to me.

Here's an example of a class that reads some data from a .csv file and returns a group of customers (another object with various fields and attributes).

public class GroupOfCustomersImporter {
    //... Call fields ....
    public GroupOfCustomersImporter(String filePath) {
        this.filePath = filePath;
        customers = new HashSet<Customer>();
        createCSVReader();
        read();
        constructTTRP_Instance();
    }

    private void createCSVReader() {
        //....
    }

    private void read() {
        //.... Reades the file and initializes the class attributes
    }

    private void readFirstLine(String[] inputLine) {
        //.... Method used by the read() method
    }

    private void readSecondLine(String[] inputLine) {
        //.... Method used by the read() method
    }

    private void readCustomerLine(String[] inputLine) {
        //.... Method used by the read() method
    }

    private void constructGroupOfCustomers() {
        //this.groupOfCustomers = new GroupOfCustomers(**attributes of the class**);
    }

    public GroupOfCustomers getConstructedGroupOfCustomers() {
        return this.GroupOfCustomers;
    }
}
```

<p>As you can see the class has only a constructor which calls some private methods to get the job done, I know that's not a good practice in general but I prefer to encapsulate all the functionality in the class instead of making the methods public in which case a client should work this way:</p>

```GroupOfCustomersImporter importer = new GroupOfCustomersImporter(filepath)
importer.createCSVReader();
read();
GroupOfCustomer group = constructGoupOfCustomerInstance();
```

I prefer this because I don't want to put useless lines of code in the client's side code bothering the client class with implementation details.

So, Is this actually a bad habit? If yes, how can I avoid it? Please note that the above is just a simple example. Imagine the same situation happening in something a little bit more complex.

答:
I think you are actually on the right track as far as wanting to hide implementation details from the client. You want to design your class so that the interface that the client sees is the simplest and most concise API that you can come up with. Not only will the client not "be bothered" with implementation details, but you will also be free to refactor underlying code without worrying that callers of that code must be modified. Reducing the coupling between different modules has some real benefit and you should definitely strive for that.

So if you follow the advice I just provided, you will end up with something you already noticed in your code, a whole bunch of logic which remains hidden behind a public interface and isn't easily accessible.

Ideally, you should be able to unit test your class against its public interface only and if it has external dependencies, you might need to introduce fake/mock/stub objects to isolate the code being tested.

However, if you do this and you still feel that you cannot easily test every part of the class, then it is very likely that your one class is doing too much. In the spirit of SRP principle, you can follow what Michael Feathers calls "Sprout Class Pattern" and extract a chunk of your original class into a new class.

In your example you have an importer class that is also responsible for reading a text file. One of your options is to extract a chunk of file reading code into a separate InputFileParser class. Now all those private functions become public and therefore easily testable.  At the same time the parser class is not something that is visible to external clients (mark it "internal", don't publish header files or simply don't advertise it as part of your API) as those will continue to use the original importer whose interface will continue to remain short and sweet.

Title: Do I suffer from encapsulation overuse?


问:
Why do new programmers seem to ignore compiler error messages/runtime exception messages?
I think we’ve all seen this. Beginners ask questions on Stack Overflow that follow the basic outline...

I’m trying to do (very vague description of the goal) but it doesn’t work/I get an error/exception. Please help!

Isn’t it bizarre that so many of them seem to consider it unnecessary to paste the error message?

I wonder what the psychology of this is. What is it about error messages that makes people initially assume that they are useless and not worth paying any attention to?

The answer I’m looking for is not “they don’t understand the error message”. That doesn’t explain why they wouldn’t consider telling anyone else who might understand it.

答:
What is it about error messages that
  makes people initially assume that
  they are useless and not worth paying
  any attention to?

Well, for me, it was a youth filled with crashing Windows 95 software with completely impenetrable error messages that usually ended with about 150 lines of hexadecimals.

I relive the same experience every time I get a nice cryptic Java stack trace which will contain 40 lines of compiler crap and Hibernate errors, and hidden very well amongst them is the actual reference to where in my app the error is.

The reason people ignore error messages and stack traces is often the error messages and stack traces are disproportionately complicated compared to the complexity of the problem. There is no reason to flush 150 lines of crap through my screen when I miss a semi-colon.


答:
As an alternative to putting a lot of method calls into your class constructor - which I agree is a habit to generally avoid - you could instead create a factory method to handle all of the extra initialization stuff that you don't want to bother the client side with. This would mean you would be exposing a method to look something like your constructGroupOfCustomers() method as public, and using it as either a static method of your class:

```<code>GroupOfCustomersImporter importer =
    new GroupOfCustomersImporter.CreateInstance();
</code>```

or as a method of a separate factory class perhaps:

```<code>ImporterFactory factory = new ImporterFactory();
GroupOfCustomersImporter importer = factory.CreateGroupOfCustomersImporter();
</code>```

Those are the just the first couple of options thought of straight off the top of my head.

It's also worth considering that you're instincts are trying to tell you something.  When your gut tells you the code is starting to smell, it probably smells, and it's better to do something about it before it reeks! Sure on the surface there may be nothing intrinsically wrong with your code per-se, however a quick recheck and a refactor will help to settle your thoughts about the issue so you can move on to other stuff confidently without worrying if you're building a potential house of cards. In this particular case, delegating some of the constructor's responsibilities to - or to be called by - a factory ensures you can exercise greater degree of control of the instantiation of your class and of it's potential future descendants.

Title: Do I suffer from encapsulation overuse?

Body:
I have noticed something in my code in various projects that seems like code smell to me and something bad to do, but I can't deal with it.

While trying to write "clean code" I tend to over-use private methods in order to make my code easier to read. The problem is that the code is indeed cleaner but it's also more difficult to test (yeah I know I can test private methods...) and in general it seems a bad habit to me.

Here's an example of a class that reads some data from a .csv file and returns a group of customers (another object with various fields and attributes).

public class GroupOfCustomersImporter {
    //... Call fields ....
    public GroupOfCustomersImporter(String filePath) {
        this.filePath = filePath;
        customers = new HashSet<Customer>();
        createCSVReader();
        read();
        constructTTRP_Instance();
    }

    private void createCSVReader() {
        //....
    }

    private void read() {
        //.... Reades the file and initializes the class attributes
    }

    private void readFirstLine(String[] inputLine) {
        //.... Method used by the read() method
    }

    private void readSecondLine(String[] inputLine) {
        //.... Method used by the read() method
    }

    private void readCustomerLine(String[] inputLine) {
        //.... Method used by the read() method
    }

    private void constructGroupOfCustomers() {
        //this.groupOfCustomers = new GroupOfCustomers(**attributes of the class**);
    }

    public GroupOfCustomers getConstructedGroupOfCustomers() {
        return this.GroupOfCustomers;
    }
}
```

<p>As you can see the class has only a constructor which calls some private methods to get the job done, I know that's not a good practice in general but I prefer to encapsulate all the functionality in the class instead of making the methods public in which case a client should work this way:</p>

```GroupOfCustomersImporter importer = new GroupOfCustomersImporter(filepath)
importer.createCSVReader();
read();
GroupOfCustomer group = constructGoupOfCustomerInstance();
```

I prefer this because I don't want to put useless lines of code in the client's side code bothering the client class with implementation details.

So, Is this actually a bad habit? If yes, how can I avoid it? Please note that the above is just a simple example. Imagine the same situation happening in something a little bit more complex.

Body:
As an alternative to putting a lot of method calls into your class constructor - which I agree is a habit to generally avoid - you could instead create a factory method to handle all of the extra initialization stuff that you don't want to bother the client side with. This would mean you would be exposing a method to look something like your constructGroupOfCustomers() method as public, and using it as either a static method of your class:

GroupOfCustomersImporter importer =
    new GroupOfCustomersImporter.CreateInstance();

or as a method of a separate factory class perhaps:

ImporterFactory factory = new ImporterFactory();
GroupOfCustomersImporter importer = factory.CreateGroupOfCustomersImporter();

Those are the just the first couple of options thought of straight off the top of my head.

It's also worth considering that you're instincts are trying to tell you something.  When your gut tells you the code is starting to smell, it probably smells, and it's better to do something about it before it reeks! Sure on the surface there may be nothing intrinsically wrong with your code per-se, however a quick recheck and a refactor will help to settle your thoughts about the issue so you can move on to other stuff confidently without worrying if you're building a potential house of cards. In this particular case, delegating some of the constructor's responsibilities to - or to be called by - a factory ensures you can exercise greater degree of control of the instantiation of your class and of it's potential future descendants.


问:
How important are UML diagrams for a successful project?
I'm in the middle of a project and I was asked to write UML diagrams (use cases,class diagram,etc). The project isn't very complex.

I was wondering if this be a waste of my time? Should I just be doing other fun stuff like writing code? And when is it not ok to build something without going through all of the conceptual phase? Is it all about complexity? And if so, how to measure it?

答:
I think UML diagrams can only be useful if they express something in a higher level of abstraction than your code.

Writing UML just for the sake of writing UML becomes unneeded bureaucracy and makes the project and the code less adaptable to changes with no benefit whatsoever.

For example, a UML class diagram showing all the classes on a package, with all their attributes and methods --something that can be easily auto-generated-- provides no value at all: it is at the same level of abstraction than your code. Plus, the code will most surely be a better source for that information because it will always be up to date, and it will probably be documented and organized in a way that is easier to know which methods/attributes/things are more important.

On the other hand, if you have concepts of a higher level of abstraction than what can be expressed expressed on the code, documenting those on a diagram can be a good idea.

For example, a diagram showing the higher level abstract modules on a complex system, with their dependencies and maybe a little description of their responsibilities and what package/namespace they map to in the source-code can be a really useful for a new team member that needs to be introduced to the project, or can also be used to figure out where a new class/functionality should be thrown.

Another example of a useful diagram could be a sequence diagram showing the high-level steps to be taken in a communication protocol. Maybe each step of those have it's little quirks and complexities, but it's probably enough to describe them in the code itself. The higher level diagram can help a programmer to understand the "big picture" of things easily without needing to worry about the complexities of each interaction.

Anyway, those are just some examples; there are lots of cases where a simple diagram can be of a lot of help. Just remember that you should be doing them only when you cannot express something in the code itself. If you find yourself using UML diagrams to explain the source-code itself, make the soruce-code more self-documenting instead.

Finally, some of the general rules that apply to code can also apply to diagrams: avoid repeating yourself, keep it simple, don't fear of changing things (just because something is documented on a UML diagram doesn't mean it can't be changed) and always think of who will be reading/maintaining those diagrams in the future (probably your future-self) when writing them :)


问:
How do I make complex SQL queries easier to write?
I'm finding it very difficult to write complex SQL queries involving joins across many (at least 3-4) tables and involving several nested conditions.  The queries I'm being asked to write are easily described by a few sentences, but can require a deceptive amount of code to complete.  I'm finding myself often using temporary views to write these queries, which seem like a bit of a crutch.  What tips can you provide that I can use to make these complex queries easier?  More specifically, how do I break these queries down into the steps I need to use to actually write the SQL code?

Note that I'm the SQL I'm being asked to write is part of homework assignments for a database course, so I don't want software that will do the work for me.  I want to actually understand the code I'm writing.

More technical details:

The database is hosted on a PostgreSQL server running on the local machine.

The database is very small: there are no more than seven tables and the largest table has less than about 50 rows.

The SQL queries are being passed unchanged to the server, via LibreOffice Base.

答:
Indentation would be the first thing to do, if you're not doing it already. Not only it's useful with even simple queries, but it is crucial when it comes to joins and queries a bit more complex than a select top 1 [ColumnName] from [TableName].

Once indented properly, nothing forbids to add comments inside the query itself, when appropriate. Don't overuse them: if the code is explicit enough, adding comments will just harm the clarity of code. But they are still welcome for the less explicit parts of the query.

Note that longer queries (including queries with comments) would mean larger bandwidth usage between your application server and your database server. Also note that unless you are working on a Google-scale product with a huge amount of requests per second, requiring an exceptional performance and resources usage, the size added by the comments may not change anything for you in terms of performance.

Enforcing the same style over tables, columns, etc. helps the readability a lot too. When a legacy database has the tables PRODUCT, users, USERS_ObsoleteDONT_USE, PR_SHIPMENTS and HRhbYd_UU, somebody is doing something very wrong.

Enforcing the same style over queries is important too. For example if you are writing queries for Microsoft SQL Server and you decided to use [TableName] instead of TableName, stick with it. If you go to a new line after a select, don't do it in only half of your queries, but all of them.

Don't use *, unless there are strong reasons to do it (like in if exists(select * from [TableName] where ...) in Microsoft SQL Server). Not only * has a negative performance impact in some (if not most) databases, but it's also not helpful for the developer who uses your query. In the same way, a developer must access the values by name, never by index.

Finally, for selects, there is nothing wrong in providing a view. For anything else, stored procedures may be also used depending on the project and the people¹ you're working² with.

¹ Some people hate stored procedures. Others don't like them for several (perfectly valid, at least for them) reasons.

² Your colleagues, the other students, your teacher, etc.


答:
None of the previous answers concern software bug causes in terms of human errors by the coder.  There's lots of research into human errors in safety critical human operator areas, such as aviation pilot errors by the FAA and NTSB.  There's also research into human memory and perceptual fallibility that might be applicable.

Unit testing is like the stall warning going off after the pilot has already approached a dangerous flight regime.  A personal study of how not to create, or how to minimize, code that produces results for unit tests to find and fail seems at minimum interesting.

Title: Formalizing programmers errors


问:
What are the best resources for learning about concurrency and multi-threaded applications?
I realised I have a massive knowledge gap when it comes to multi-threaded applications and concurrent programming. I've covered some basics in the past, but most of it seems to be gone from my mind, and it is definitely a field that I want, and need, to be more knowledgeable about.

What are the best resources for learning about building concurrent applications? I'm a very practical oriented person, so if said book contains concrete examples the better, but I'm open to suggestions. I personally prefer to work in pseudocode or C++, and a slant toward game development would be best, but not required.

答:
I have found this free threading resource put up by Joe Albahari excellent ...

Threading in C#

Its slanted towards C# but the concepts are entirely applicable to other languages. He also provides the tutorial as a PDF download in english and several other languages. I would recommend it due to the combination of example code, step by step explanations of the code and excellent sequence and state diagrams accompanying the examples.

The tutorial is in five parts:

Getting started

Basic synchronisation

Using threads

Advanced threading

Parallel programming

Its available in book form here: C# 4.0 in a Nutshell (chapters 23 and 24)


问:
BSD Software license usage
We are a company and we want to use 30% of the BSD opensource software to plug and play it with our source code, can we do that. Further this program will not be distributed and only will be accessed by our clients using our own software. Is it possible for us to do the above without any restrictions.

Kindly give me feedback on the above soon as possible.

答: BSD means you can pretty much do what you want with it except claim it was our own invention - read the licence</p>

Title: BSD Software license usage


答:
Adding my own answer, since it ended up too long for a comment.

You are absolutely right that encapsulation and testing are pretty contrary - if you hide almost everything, it's hard to test.

You could, however, make the example more testable by giving a stream rather than filename - that way you just supply a known csv from memory, or a file if you want. It will also make your class more robust when you need to add http support ;)

Also, look into using lazy-init:

```<code>public class Csv
{
  private CustomerList list;

  public CustomerList get()
  {
    if(list == null)
        load();
     return list;
  }
}
</code>```

Title: Do I suffer from encapsulation overuse?

Body:
Adding my own answer, since it ended up too long for a comment.

You are absolutely right that encapsulation and testing are pretty contrary - if you hide almost everything, it's hard to test.

You could, however, make the example more testable by giving a stream rather than filename - that way you just supply a known csv from memory, or a file if you want. It will also make your class more robust when you need to add http support ;)

Also, look into using lazy-init:

public class Csv
{
  private CustomerList list;

  public CustomerList get()
  {
    if(list == null)
        load();
     return list;
  }
}


问:
What's the best way to review a code before it's committed to the trunk? (SVN)
What's the best way to review a code before it's committed to the SVN trunk? One idea that I am thinking of is to having the developer to commit his code to a branch and then reviewing his code while merging the branch revisions into the trunk. Is this a good practice? If not, what else could be done to review a code before it's committed to the trunk?</p>

答:
There are two schools of though - what you propose or "review before commit". Most of the The differences can be seen as negatives and/or positives. - eg No tracking of changes caused by a review - do you want to see these as discrete commits, or are you only interested in the final work?

Review before commit - no branching required (although it can done if desired), must give reviewers access to working folders. Code can be changed during and after review with no tracking. Corrections caused by the review do not appear in the repository.

Review After Commit (on a branch)  - Need to spin a branch for each review (although this may be in the workflow already). Code submitted for review cannot be changed without tracking of the changes. Someone has to merge the reviewed branches, and keep track of whats been reviewed and what hasn't.

It largely depends on the team culture and experience. Whats you trust model, what it the main purpose for reviews?  I personally prefer review after commit, as it allows changes as a result of review to be tracked. We now use Git and Gerrit as they provide a nice balance between the two options.


答:
The usual IANAL applies; if you need legal advice, consult a lawyer.

That said, the spirit of the BSD license is that you can do pretty much anything you like, except claim you wrote code that you did not write.

There are different flavors of the BSD license; some include an attribution clause (if you redistribute, you must attribute code you derived from to the original authors) and / or a non-endorsement clause (you cannot use the original product name, nor the names of the original authors, to endorse your derived product). But other than that, you are free to derive and reuse as you see fit.

For some perspective: even Windows includes a few pieces of BSD-licensed code.

Title: BSD Software license usage

Body:
We are a company and we want to use 30% of the BSD opensource software to plug and play it with our source code, can we do that. Further this program will not be distributed and only will be accessed by our clients using our own software. Is it possible for us to do the above without any restrictions.

Kindly give me feedback on the above soon as possible.


答:
I find it useful at the initial design stage to get ideas on paper or on the whiteboard. I've mainly used UML class diagrams, without a strict adherence to the standards. Its useful to revisit your UML original design when you're part way through and also at the end of the project. It has helped me to look at a codebase at a higher level of abstraction that you ever can just by reading through code, and has even helped to spot potential bugs.

There's a good point made here by ragu.pattabi distinguishing between two kinds of UML ...

I think the agile flavor of UML (e.g. quick white board sketch) is
  more successful than the waterfall flavor of UML (e.g. elaborate
  diagram with all gory detail for documentation, code generation, etc
  to make the document savvy managers happy).

When UML was seen as a 'must have' skill (10 years ago or more) I was probably against it due to the opinionated views of its many fans at the time. But now that its fallen out of favor, I find myself seeing it for what it is - a useful tool that has merit but is not the silver bullet of software development.


问:
INI files or Registry or personal files?
I want to save the configuration of my project which includes

Screen size

Screen position

Folder paths

Users settings and so on.

The standard places where you can save these are configuration values are:

Registry

INI files

Personal files (like *.cfg)

How do you choose between these places? Also, are there any pros and cons of using any of them?

答:
To expand Jeff D's suggestion of YAML, here's a brief intro.

YAML is similar to JSON (in fact, JSON is a subset of YAML since version 1.2 of the YAML standard, and can thus valid JSON can be parsed by YAML parsers).  At first glance, the main difference being that YAML (by default) uses indentation rather than bracketing to show hierarchy.  There is also a noticable lack of quotes for strings.  A quick example from above:

```<code>configuration:
  window:
    width:       600
    height:      350
    position:
      x:         400
      y:         200
  paths:
    path1:       some/random/path
    path2:       some/other/random/path
  user:
    name:        Joe Soap
    preference:  YAML
</code>```

See Wikipedia's YAML page for better examples.  Support for YAML exists for most major languages (see yaml.org for details).

Body:
To expand Jeff D's suggestion of YAML, here's a brief intro.

YAML is similar to JSON (in fact, JSON is a subset of YAML since version 1.2 of the YAML standard, and can thus valid JSON can be parsed by YAML parsers).  At first glance, the main difference being that YAML (by default) uses indentation rather than bracketing to show hierarchy.  There is also a noticable lack of quotes for strings.  A quick example from above:

configuration:
  window:
    width:       600
    height:      350
    position:
      x:         400
      y:         200
  paths:
    path1:       some/random/path
    path2:       some/other/random/path
  user:
    name:        Joe Soap
    preference:  YAML

See Wikipedia's YAML page for better examples.  Support for YAML exists for most major languages (see yaml.org for details).


答: Instead of temporary views, use the WITH clause. This makes it much easier to break down large queries into more readable smaller parts.</p>

Title: How do I make complex SQL queries easier to write?

Body:
I'm finding it very difficult to write complex SQL queries involving joins across many (at least 3-4) tables and involving several nested conditions.  The queries I'm being asked to write are easily described by a few sentences, but can require a deceptive amount of code to complete.  I'm finding myself often using temporary views to write these queries, which seem like a bit of a crutch.  What tips can you provide that I can use to make these complex queries easier?  More specifically, how do I break these queries down into the steps I need to use to actually write the SQL code?

Note that I'm the SQL I'm being asked to write is part of homework assignments for a database course, so I don't want software that will do the work for me.  I want to actually understand the code I'm writing.

More technical details:

The database is hosted on a PostgreSQL server running on the local machine.

The database is very small: there are no more than seven tables and the largest table has less than about 50 rows.

The SQL queries are being passed unchanged to the server, via LibreOffice Base.


答:
Any piece of development that needs a review would have to be in a separate branch.  So, the branch should already exist before the time comes for review.  Then the step would need to be:

Review

Revise (possibly)

loop back to Review (possibly)

Merge into trunk

Merging is the difficult bit.  The longer the branch stays independent, the harder it is going to be to merge it back into the trunk.  (It might also be harder to test.)

Cross-merging is a possible solution.  Before merging into the trunk (step 4, or even earlier, say before step 3 or step 1), merge the trunk into the branch.  The developer can do it and test it.  Then the branch catches up with the trunk and it becomes easier to merge it into the trunk.  Merging into the trunk is best done by you, or whoever is in charge of the trunk.

Some people try rebase instead of cross-merge.  Some people argue that rebase is evil.  That is another debate.

Title: What's the best way to review a code before it's committed to the trunk? (SVN)

Body: What's the best way to review a code before it's committed to the SVN trunk? One idea that I am thinking of is to having the developer to commit his code to a branch and then reviewing his code while merging the branch revisions into the trunk. Is this a good practice? If not, what else could be done to review a code before it's committed to the trunk?</p>


答:
Before committing run 'svn diff' to generate a patch file.

Send patch file to reviewer who applies it to a clean copy of the trunk.

Reviewer goes over changes using difference viewer of choice.

Reviewer performs build and runs tests.

If all goes well tell developer they can check their changes. If

there are problems the developer goes back to step 1.


问:
Catching an error?
Is catching an error with try ... catch a better practice than catching an error with proper analysis/error check? For instance, removing from an empty list: Does surround with a try catch clause considered as a more efficient way than testing if the list is empty beforehand?Or is it the same? Thanks.

P.S: If a similar question was previously asked on the forum please feel free to refer it.

答:
Simple answer: Don't use try-catch for situations where you can check the failure condition in code.

Try-catch should not be used for controlling program flow.

See Vexing Exceptions - it's focussed on C# but is applicable to exception handling in all languages.

Title: Catching an error?


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Comments that are so verbose that if there were an English compiler, it would compile and run perfectly, yet doesn't describe anything that the code doesn't.

//Copy the value of y to temp.
temp = y;
//Copy the value of x to y.
y = x;
//Copy the value of temp to x.
x = temp;
```

<p>Also, comments on code that could have been done away with had the code adhered to some basic guidelines:</p>

<pre class="lang-c prettyprint-override"><code>//Set the age of the user to 13.
a = 13;
</code>```

Body:
Comments that are so verbose that if there were an English compiler, it would compile and run perfectly, yet doesn't describe anything that the code doesn't.

//Copy the value of y to temp.
temp = y;
//Copy the value of x to y.
y = x;
//Copy the value of temp to x.
x = temp;

Also, comments on code that could have been done away with had the code adhered to some basic guidelines:

//Set the age of the user to 13.
a = 13;


答:
There's the ideal world, and then there's the real world.

In the ideal world, all your code is tested, so you can be sure that anything that gets checked in will either work or you'll know it's broken because it fails one or more tests. Plus, anyone not so experienced will be paired with someone who is experienced, so code reviewing is done on-the-fly (you commit as you go).

In the real world, things are different. Business wants that change live now and will tell you, with a perfectly straight face, that yes, you'll get time to clean up the code and add test cases later. You probably won't have time to code review everything and the percentage of code that is covered by tests continually decreases. The main reason for code review is for junior developers to learn from senior developers (when there's time for that) by having a more experienced person look over changes and suggest "better ways of doing things (TM)". You'll have senior developers just committing unreviewed code. Branching just for a code review and then merging is a huge waste of time. One way to overcome this problem is to declare a regular weekly 2-hour (or so) team meeting where you pick one or two recent changes people worked on at short notice and get their authors to "present" their approach by looking at the code together on a projector or something This can lead to some interesting discussions (typically goes off-topic quite a bit) but generally improves everyone's understanding of how to do it right. Plus the pressure of possibly having to present your code makes some people do it better ;-)

Or you might be lucky and get to work in a real-world environment where it's not so hectic, programmers are actually appreciated for what they do instead of abused, and there's time to do everything right. In which case my answer would be: try some of the different methods suggested in answers here and see which one fits your team and the way you work best.


问:
Is there any reason in a Java program for a special naming for a function arguments?
I'd like to know, why would I want to have a special prefixes for a function arguments, like "p_name", "p_age", "p_sex"? On the one hand it helps to distinguish parameter from local variable or field further in the function body, but would it help? On the other hand, I didn't saw such naming recommendations anywhere including official Java language conventions. Please advise any reasons for using such naming policy</p>

答: You are right, distinguishing variables from parameters and fields at a glance is pretty much the only motivation for doing this. And it isn't a very good one; if your method is so long that such memory hints are necessary, it is too long in the first place. There is a reason why it's strongly recommended to keep methods small enough that they can be taken in completely in one glance, and understanding the roles of all the variables involved is a large part of that.</p>


答:
From a business perspective, refactoring is speculative investment - investing time and effort (money) now, in the hope that it will save more time and effort (money) sometime in the future.

Without entering into the debate as to how much the effort to refactor will save in the furture (This depends on too many variables for it to be a meanignful discussion here), it is clear the time to refactor is when the "net present value" of the cost leaving it exceeds the cost of doing now.

Thats easy, except you have no idea how much the furture will cost. You also need to factor in all the normal financial planning ideas such as Return on investment, risk management (value of brand, legal liabilty, insurable vs non insurable risk), oppertuniy cost etc.

In most instances, deciding when to refactor is best left to the people who run the business. Despite what many posters on this forum vocalise, managers usually know more far about running a business than programmers. They have a bigger picture in mind that includes maximising the return to the shareholder. It's rare that fixing things that are not broken contributes to this, code is no exception.

Edit : I have read an interesting article about maintaince schedules on critical infrastructure. The gist is that the movement is away from routine maintaiance (refactor) to repair when needed (fix bugs). The main difference is the monitoring levels - for instance a nuclear power plant monitors in great detail, and fixes when "broken" but well before failure. What has been found is that fixing to a maintaince scheule not only costs more, but is less reliable due outages caused by the maintaince program. A similar idea is required for software - refactor the bits that are about to break - which you can only know by measurement.


答:
Such a scheme makes little sense for two reasons:

You should count on your IDE to provide means to distinguish parameters from other variables, either through intellisense hints or syntax coloring.

If you wish to further distinguish fields from local variables/parameters, you can prefix them with this.. I believe its use is up to discussion, however at least in case of Java it seems to be a widespread practice.

However, if it's an implemented coding standard in your project, you can question and discuss it, but in the end should abide by it, no matter how senseless it may seem.

Title: Is there any reason in a Java program for a special naming for a function arguments?

Body: I'd like to know, why would I want to have a special prefixes for a function arguments, like "p_name", "p_age", "p_sex"? On the one hand it helps to distinguish parameter from local variable or field further in the function body, but would it help? On the other hand, I didn't saw such naming recommendations anywhere including official Java language conventions. Please advise any reasons for using such naming policy</p>


问:
Using HashTable without overriding hashcode()
Today I was asked this question during an interview:

What will happen if we do not override the hashcode method for our
  class, then add it to HashTable and then try to get objects?

What could go wrong?

答: The answer is: similar objects (all fields having equal values) would not create the same hash code, so you would need exactly the same (identical) object that was used for put to retrieve from hashtable, which is not feasible in most cases.