答:
Keep in mind that the ability to read code you haven't written is a very valuable skill, probably more valuable than writing code. Unfortunately, this is widely understated and under-taught at schools.

What I am trying to say is that it's normal that you don't always understand code upon reading it the first time (just like it's normal that you don't write perfect code the first time). If you accept that it takes time to get a foreign code, than you won't mind putting in the extra effort. A small summary:

Unit tests would be ideal, but not always realistic; especially if you work in a large organization with heavy bureaucracy.

Learn to use your Version Control system properly; you'll never break the existing (not really never, but it's a good safety net).

Don't assume it's bad simply because you don't understand it instantly. Don't assume it's good simply because it works. The important thing is that you understand the previous maintainer's style of code and adapt your added lines to his style. The maintainer coming after you will thank you for it.

In some companies, unfortunately, the difficulty of reading code can be underestimated. This is common in large corporations with rigid processeses. They'd often (implicitly) prefer you push code that works quickly rather than take your time to write something clean. I'll leave it up to you to decide where your team stands on this point.

Finally, never forget that reading code is a skill. The more you do it, the better you'll get at it. Another way to say this is that the only way to get good at it is to practice it many times. Like mentionned above, reading code is and will be a much larger part of your job than writing is.

Title: Working on someone else's code


问:
Working on someone else's code
I have hardly a year's experience in coding. After I started working, most of the time I would be working on someone else's code, either adding new features over the existing ones or modifying the existing features. The guy who has written the actual code doesn't work in my company any more. I am having a hard time understanding his code and doing my tasks. Whenever I tried modifying the code, I have in some way messed with the working features. What all should I keep in mind, while working over someone else's code?</p>

答:
Judging from your problems with inadvertently breaking stuff, I'm going to assume that the code isn't covered by automated tests. Step #0 would be to immediately order and read Working Effectively with Legacy Code by Michael Feathers. It is simply invaluable.

The basic steps I would suggest:

Cover the code with tests covering the current functionality.

Refactor until understandable.

Write a test for the new or modified functionality.

Implement the new functionality.

Refactor until satisfaction.

I deliberately leave out specifying the flavor of the tests (unit, integration, ...) - just get some kind of automated test coverage.

(and, yes, follow the coding style in terms of layout and naming)

ContentLicense: CC BY-SA 3.0

Title: Working on someone else's code


答:
As mentioned earlier: welcome to the real world. I can only agree with earlier answers. I'll only wish to extend the answer with my work experience about time estimates.

A good suggestion it to make you boss clear, it will take time to learn how the other developer(s) think. Usually you will experience that the current solution often depends on the age and experience of the developer.

If you are lucky, the task at hand has to be analysed and understanding the documentation will help you a lot (but this is often not the case).

My experience is that when modifying others code, try not to change code which does not involve your current task. You may know a better solution or it could be written in a more intuitive way, but changing it often leads to problems like:

The task will take longer and your boss will not understand it.

The code you change must be tested, and it costs. The current solution has been tested and approved.

It will be difficult to see what changes solves the current task, and which are 'just' corrections.

But do not hesitate to tell your boss, if you see something you think should be different (it just shows you can think).

Finally, make sure that you have enough time to make the solution. A faster solution comes with experience. But there is seldom a fast solution, as this is the first/major reason for errors and unmaintainable code.

Title: Working on someone else's code

Body: I have hardly a year's experience in coding. After I started working, most of the time I would be working on someone else's code, either adding new features over the existing ones or modifying the existing features. The guy who has written the actual code doesn't work in my company any more. I am having a hard time understanding his code and doing my tasks. Whenever I tried modifying the code, I have in some way messed with the working features. What all should I keep in mind, while working over someone else's code?</p>


问:
How to unit test large legacy systems?

Possible Duplicate:

  Best practices for retrofitting legacy code with automated tests

When working in large legacy systems (large systems with no unit testing ever) I often come across people saying use unit testing as a tool against possible bugs. I wonder if somebody have tried it on large systems with no unit testing at all.

Of course it is easy to say unit testing helps ,but in large systems it can hugely time consuming process. It can take months if not years to fully unit test each part of the application .

When you are asked to make a functionality which is modification of existing functionality or adding new functionality to the application, how would you go about it? Of course there will be lots of instances where code in different classes will look similar and you would want to re-factor those classes which without proper unit testing can and most likely will open a can of worms.

So how would you go about unit testing large applications? And what other measures would you use to reduce possible bugs from your coding (of course some bugs will probably remain anyway)?

答:
Covering legacy code with unit tests is a long, difficult, step by step process. But it is doable, and is an absolute must if you are maintaining a product with a long expected lifetime (i.e. more than a year - note that the lifetime of most project significantly extends their originally planned lifetime).

When I joined our current project close to 3 years ago, there existed less than 50 unit test cases and the coverage was below 0,5%. Around the end of last year, we had over 2600 unit tests and coverage was over 36%. (Since then development has been largely stalling.) During the same time, code size went down from 106 to 67 KLOC, and technical debt (as measured by Sonar) from over $513K to $213K - while new functionality was added too.

So yes, it is possible. But only with a management that supports code quality improvement and long term maintainability, and is willing to spend significant time and resources on it.

If you have such a management, my first advice is: run, don't walk, to buy Working Effectively With Legacy Code by Michael Feathers.

Then start adding unit tests. The simplest tactic is to add unit tests before you need to touch any part of the code, to cover the changing part(s) to some reasonable extent. Sometimes you just add a single test case at a time to cover a simple change in a huge class. Sometimes you have more time, so you can construct a more comprehensive test suite to fully cover a bigger method, or even several of them. Keep adding unit tests - the little changes will add up to ever greater sums in the long term.

Title: How to unit test large legacy systems?


问:
Dependency injection: How to sell it
Let it be known that I am a big fan of dependency injection (DI) and automated testing. I could talk all day about it.

Background

Recently, our team just got this big project that is to built from scratch. It is a strategic application with complex business requirements. Of course, I wanted it to be nice and clean, which for me meant: maintainable and testable. So I wanted to use DI.

Resistance

The problem was in our team, DI is taboo. It has been brought up a few times, but the gods do not approve. But that did not discourage me.

My Move

This may sound weird but third-party libraries are usually not approved by our architect team (think: "thou shalt not speak of Unity, Ninject, NHibernate, Moq or NUnit, lest I cut your finger"). So instead of using an established DI container, I wrote an extremely simple container. It basically wired up all your dependencies on startup, injects any dependencies (constructor/property) and disposed any disposable objects at the end of the web request. It was extremely lightweight and just did what we needed. And then I asked them to review it.

The Response

Well, to make it short. I was met with heavy resistance. The main argument was, "We don't need to add this layer of complexity to an already complex project". Also, "It's not like we will be plugging in different implementations of components". And "We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit".

Finally, My Question

How would you handle my situation? I am not good in presenting my ideas, and I would like to know how people would present their argument.

Of course, I am assuming that like me, you prefer to use DI. If you don't agree, please do say why so I can see the other side of the coin. It would be really interesting to see the point of view of someone who disagrees.

Update

Thank you for everyone's answers. It really puts things into perspective. It's nice enough to have another set of eyes to give you feedback, fifteen is really awesome! This are really great answers and helped me see the issue from different sides, but I can only choose one answer, so I will just pick the top voted one. Thanks everyone for taking the time to answer.

I have decided that it is probably not the best time to implement DI, and we are not ready for it. Instead, I will concentrate my efforts on making the design testable and attempt to present automated unit testing. I am aware that writing tests is additional overhead and if ever it is decided that the additional overhead is not worth it, personally I would still see it as a win situation since the design is still testable. And if ever testing or DI is a choice in future, the design can easily handle it.

答:
Taking a couple of the counter arguments:

"We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit".

"its not like we will be plugging in different implementations of components".

What you want is for the system to be testable. To be easily testable you need to be looking at mocking the various layers of the project (database, communications etc.) and in this case you will be plugging in different implementations of components.

Sell DI on the testing benefits it gives you. If the project is complex then you're going to need good, solid unit tests.

Another benefit is that, as you are coding to interfaces, if you come up with a better implementation (faster, less memory hungry, whatever) of one of your components, using DI makes it a lot easier to swap out the old implementation for the new.

What I'm saying here is that you need to address the benefits that DI brings rather than arguing for DI for the sake of DI. By getting people to agree to the statement:

"We need X, Y and Z"

You then shift the problem. You need to make sure that DI is the answer to this statement. By doing so you co-workers will own the solution rather than feeling that it's been imposed on them.

Title: Dependency injection: How to sell it


答:
I'm sorry to say that the problem you have, given what your coworkers have said in your question, is in political nature rather than technical. There are two mantras that you should keep in mind:

"It is always a people problem"

"Change is scary"

Sure, you can bring up a lot of counter arguments with solid technical reasons and benefits, but that will put you in a bad situation with the rest of the company. They have a stance already that they don't want it (because they're comfortable with how things are working now). So it might even hurt your relationship with your fellow colleagues if you keep being persistent about it. Trust me on this because it has happened to me and eventually got me fired several years ago (young and naive that I was); this is a situation you don't want to get yourself into.

The thing is, you need to attain some level of trust before people will go so far as to change their current way of working. Unless you are in a position where you have lots of trust or you can decide these kinds of things, such as having the role of an architect or tech lead, there is very little you can do to turn your colleagues around. It will take a lot of time with persuasion and effort (as in taking small improving steps) to gain trust in order to get your company culture to turn around. We're talking about a timespan of many months or years.

If you find that the current company culture is not working with you then at least you know one other thing to ask on your next job interview. ;-)

Title: Dependency injection: How to sell it

Body:
Let it be known that I am a big fan of dependency injection (DI) and automated testing. I could talk all day about it.

Background

Recently, our team just got this big project that is to built from scratch. It is a strategic application with complex business requirements. Of course, I wanted it to be nice and clean, which for me meant: maintainable and testable. So I wanted to use DI.

Resistance

The problem was in our team, DI is taboo. It has been brought up a few times, but the gods do not approve. But that did not discourage me.

My Move

This may sound weird but third-party libraries are usually not approved by our architect team (think: "thou shalt not speak of Unity, Ninject, NHibernate, Moq or NUnit, lest I cut your finger"). So instead of using an established DI container, I wrote an extremely simple container. It basically wired up all your dependencies on startup, injects any dependencies (constructor/property) and disposed any disposable objects at the end of the web request. It was extremely lightweight and just did what we needed. And then I asked them to review it.

The Response

Well, to make it short. I was met with heavy resistance. The main argument was, "We don't need to add this layer of complexity to an already complex project". Also, "It's not like we will be plugging in different implementations of components". And "We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit".

Finally, My Question

How would you handle my situation? I am not good in presenting my ideas, and I would like to know how people would present their argument.

Of course, I am assuming that like me, you prefer to use DI. If you don't agree, please do say why so I can see the other side of the coin. It would be really interesting to see the point of view of someone who disagrees.

Update

Thank you for everyone's answers. It really puts things into perspective. It's nice enough to have another set of eyes to give you feedback, fifteen is really awesome! This are really great answers and helped me see the issue from different sides, but I can only choose one answer, so I will just pick the top voted one. Thanks everyone for taking the time to answer.

I have decided that it is probably not the best time to implement DI, and we are not ready for it. Instead, I will concentrate my efforts on making the design testable and attempt to present automated unit testing. I am aware that writing tests is additional overhead and if ever it is decided that the additional overhead is not worth it, personally I would still see it as a win situation since the design is still testable. And if ever testing or DI is a choice in future, the design can easily handle it.


答:
I think one of their biggest concern is in fact just the opposite:
DI is not making the project complex.  In most case it is reducing lots of complexity.

Just think without DI, what are you going to get the dependent object/component you need? Normally it is by lookup from a repository, or getting a singleton, or instantiating yourself.

The former 2 involves extra code in locating the dependent component, in DI world, you didn't do anything to perform the lookup.  The complexity of your components is in fact reduced.

If you are instantiating yourself in some cases that is not appropriate, it is even creating more complexity.  You need to know how to create the object correctly, you need to know what values to initialize the object to a workable state, all these create extra complexity to your code.

So, DI is not making the project complex, it is making it simpler, by making components simpler.

Another big argument is, you are not going to plug different implementation.  Yes, it is true that in production code, it is not common to have many different implementation in real production code.  However there is one major place that need different implementation: Mock/Stub/Test Doubles in Unit Tests.  To make DI works, in most case it relies on interface-driven development model, in turns it makes mocking/stubbing in unit tests possible.  Apart from replacing implementation, "interface-oriented design" also makes cleaner and better design.  Of course you can still design with interface without DI.  However, Unit tests and DI is pushing you to adopt such practices.

Unless your "gods" in company do think that: "simpler code", "unit tests", "modularization", "single responsibility", etc are all something they against, there should be no reason for them to reject using DI.

Title: Dependency injection: How to sell it


答:
"We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit".

The benefit is its promotes designing to interfaces and allows easy mocking. Which consequently facilitates unit testing.  Unit testing ensures reliable, modular and easily maintainable code.  If your boss still maintains its a bad idea, well there is nothing you can do - its accepted industry best practice that they are arguing against.

Get them to try writing a unit test with a DI framework and mocking library, they will soon learn to love it.

Title: Dependency injection: How to sell it


答:
I think that ChrisF is into something right. Don't sell DI in itself. But sell the idea about unit testing the code.

One approach to get a DI container into the architecture could be to then slowly let the tests drive the implementation into something that sits well with that architecture. E.g. lets say you are working on a controller in an ASP.NET MVC application. Say you write the class like this:

```<code>public class UserController {
    public UserController() : this (new UserRepository()) {}

    public UserController(IUserRepository userRepository) {
        ...
    }

    ...
}
</code>```

That allows you to write unit tests decoupled from the actual implementation of the user repository. But the class still works without a DI container to create it for you. The parameterless constructor will create it with the default repository.

If you coworkers can see that this leads to much cleaner tests, maybe they can realize that is a better way. Maybe you can get them to start coding like that.

Once they have realized that this is a better design than the UserController knowing about a specific UserRepository implementation, you can take the next move, and show them that you can have a component, the DI container, that can automatically provide the instances you require.

Title: Dependency injection: How to sell it

Body:
I think that ChrisF is into something right. Don't sell DI in itself. But sell the idea about unit testing the code.

One approach to get a DI container into the architecture could be to then slowly let the tests drive the implementation into something that sits well with that architecture. E.g. lets say you are working on a controller in an ASP.NET MVC application. Say you write the class like this:

public class UserController {
    public UserController() : this (new UserRepository()) {}

    public UserController(IUserRepository userRepository) {
        ...
    }

    ...
}

That allows you to write unit tests decoupled from the actual implementation of the user repository. But the class still works without a DI container to create it for you. The parameterless constructor will create it with the default repository.

If you coworkers can see that this leads to much cleaner tests, maybe they can realize that is a better way. Maybe you can get them to start coding like that.

Once they have realized that this is a better design than the UserController knowing about a specific UserRepository implementation, you can take the next move, and show them that you can have a component, the DI container, that can automatically provide the instances you require.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
In one job we were forced to use some weird form of Hungarian notation in the database.

I can't remember the details, but from memory, each field name had to contain:

No vowels

All uppercase letters

A reference to the table

A data type indicator

A data length

A nullable indicator

For example, the column holding a person's first name might be called: PRSNFRSTNMVC30X (Person table, First Name column, Varchar 30 characters, Not Null)


问:
Why does adding more people to a late project make it later?
It's a fairly common adage that adding more programmers to a late project will make matters worse. Why is this?</p>

答:
In addition to the other answers: Another factor to consider is communication.

The worst case for the amount of communication channels on a team (which isn't uncommon), is a complete graph. As you can imagine, adding in just 1 developer can increase the communication channels a lot. With more streamlined methods of communication, the impact is less... but it still adds up.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


答:
In my opinion, the fastest way to learn someone else´s code, (especially when changes triggers unexpected behavior as you describe) is to step through the code using a debugger.

Begin with stepping through what seems to be the main loop / main methods of the program. Use the step into and step out functions to see what different methods does. This will teach you the general structure of the code.

After that, divide and conquer by stepping through and learning the different parts of the program on a deeper level. In most debuggers you can study variables and their current values. Study how they change and when.

Set out breakpoints on methods that trigger behaviors that concerns you. For example if you are trying to change a text in the program, and the text keep changing back to the original value, set breakpoints on all places where the text is changed, or try to move all these changes to one single method. Use the call stack to see from where this method is called, etc etc.

If changing a line of code causes unexpected changes on other places, put a breakpoint on that line, and see what happens there, for example by checking the values of current variables in scope, using step into, or the call stack to see from where the call came.

By doing this alot, you will start to learn the structure of the code surprisingly fast. I started out just like you did on my first programming jobs, with lots of code that had been written many years ago and been changed by many people through many years. The code was not mine only since there where other people working on it at the same time. I couldn't rewrite it all at that point. Writing tests for all that code would have taken me months or years. The debugger really saved me, don't know how I would have learned the code without it...

Title: Working on someone else's code


答:
I have seen projects that took DI to an extreme in order to unit test and mock objects. So much so that the DI configuration became the programming language in itself with as much configuration needed to get a system running as actual code.

Is the system suffering right now because of a lack of appropriate internal API's that cannot be tested? Are you hoping that switching the system over to a DI model would allow you to unit test better? You don't need a container in order to unit test your code. Using a DI model would allow you to unit test it easier with Mock objects, but it is not required.

You don't need to switch the whole system over to be DI compatible at once. You shouldn't be arbitrarily writing Unit tests either. Refactor code as you come across it in your feature and bug working tickets. Then ensure that the code you've touched is easily testable.

Think about CodeRot as a disease. You don't want to start arbitrarily hacking away at things. You have a patient, you see a sore spot, so you start fixing the spot and the things around it. Once that area is clean you move on to the next. Sooner or later you'll have touched the majority of the code and it didn't require this "massive" architectural change.

I do not like that DI and Mock testing are mutually exclusive. And after seeing a project that went, for lack of a better word, crazy using DI, I'd be weary also without seeing the benefit.

There are some places that makes sense to use DI:

The Data Access Layer to swap out strategies for storying data

Authentication and Authorization Layer.

Themes for the User Interface

Services

Plugin extension points that your own system or third-party can use.

Requiring each developer to know where the DI configuration file is (I realize containers can be instantiated through code, but why would you do that.) when they want to perform a RegEx is frustrating. Oh I see there is IRegExCompiler, DefaultRegExCompiler and SuperAwesomeRegExCompiler. Yet no where in the code can I do analysis to see where Default is used and SuperAwesome is used.

My own personality would react better if someone showed me something that was better, then trying to convince me with their words. There is something to be said about someone that would put in time and effort to make the system better. I don't find that many developers care enough to make the product truly better. If you could go to them with real changes in the system and show them how it made it better and easier for you, that is worth more than any online research.

In summary, the best way to effect change into a system is to slowly make the code you are currently touching better with each passing. Sooner or later you'll of been able to transform the system into something better.

Title: Dependency injection: How to sell it


答:
From what you are writing, not DI itself is taboo, but the use of DI containers, which is a different thing. I guess you will get no problems with your team when you just write independent components which get other components they need passed, for example, by the constructor.  Just don't call it "DI".

You may think for such components not to use a DI container is tedious, and you are right, but give your team the time to find that out for themselves.

Title: Dependency injection: How to sell it


问:
Which is best for learning how to do a certain thing: writing your own or looking at someone else's?
Often when I'm writing code to do a certain thing, I'm faced with either writing my own or using someone else's code. Assume here that this "thing" is something that I've never done before and am interested in learning how it's done.

Which would you say is better from a learning perspective: try writing your own solution; or looking at code by someone else? I've always written my own code if I have an idea on how to do it, but resorted to looking at someone else's when I don't have a clue. I believe that the best is probably a combination of both: make your own attempt and then look at how someone else did.

答:
If I really want to learn how to do X and someone's got a sample online, going through the sample really speeds up how quickly I can write it myself.  Stepping through their code gives you one possible starting place on where the code can end up.  I may end up with my own code that is no where near the example, but the example got me to that decision.

If the sample is gold code, then I may incorporate it into what I'm doing, but 9 times out of 10 the sample is not quite what I was looking for.  In those cases I'll use what I learned with the sample and build my own.


答:
Think of it like performing an operation on a person.

You look inside for the problem you need to fix and notice that most of the arteries, etc. are not set up the way you would do it - so you cut and chop them around until it looks right to you and then fix the problem.

Amazingly your patient dies almost immediately.

Legacy applications are the same. They already have a way of working - you need to understand the various components in the software and how they relate to each other and then make your change so it works the same way. It is not a exciting as letting your creativity go wild, but you can do that on personal projects.

I would ask a senior engineer to sit down with you for an hour or so every Monday and explain a different aspect of the system. Make notes of what he says and email the notes to him and your manager to see if your manager has anything to add. You should get up to speed quite quickly this way.

As for how to not break things, first of all make sure you understand what the system does. Test before - make your change - test afterwards. There are no magical formulas; as you gain experience you will get better - or get fired I guess!

Title: Working on someone else's code


答:
I don't think that you can sell DI any more, because this is a dogmatic decision (or, as @Spoike called it more politely, political).

In this Situation arguing with widely accepted best practices like SOLID design principles is not possible any more.

Somebody who has more political power than you has made a (maybe wrong) decision to not use DI.

You on the other side have opposed this decision by implementing you own container because using an established container was forbidden. This policy of faits accomplis that you tried might have made the situation more worse.

Analysis

In my opinion, DI without testdriven development (TDD) and unit testing has no significant benefit that outweighs the initial extra costs.

Is this issue really about

we do not want DI?

or is this more about

tdd/unittesting is a waste of resources?

[Update]

If you see your project from the classic mistakes in project management view, you see

```<code>#12: Politics placed over substance.
#21: Inadequate design.
#22: Shortchanged quality assurance.
#27: Code-like-hell programming.
</code>```

while the others see

```<code>#3: Uncontrolled problem employees.
#30: Developer gold-plating.
#32: Research-oriented development.
#34: Overestimated savings from new tools or methods.
</code>```

Title: Dependency injection: How to sell it

Body:
I don't think that you can sell DI any more, because this is a dogmatic decision (or, as @Spoike called it more politely, political).

In this Situation arguing with widely accepted best practices like SOLID design principles is not possible any more.

Somebody who has more political power than you has made a (maybe wrong) decision to not use DI.

You on the other side have opposed this decision by implementing you own container because using an established container was forbidden. This policy of faits accomplis that you tried might have made the situation more worse.

Analysis

In my opinion, DI without testdriven development (TDD) and unit testing has no significant benefit that outweighs the initial extra costs.

Is this issue really about

we do not want DI?

or is this more about

tdd/unittesting is a waste of resources?

[Update]

If you see your project from the classic mistakes in project management view, you see

#12: Politics placed over substance.
#21: Inadequate design.
#22: Shortchanged quality assurance.
#27: Code-like-hell programming.

while the others see

#3: Uncontrolled problem employees.
#30: Developer gold-plating.
#32: Research-oriented development.
#34: Overestimated savings from new tools or methods.


问:
Excellent knowledge of C++
I recently saw a recruiting page for a software company where one of the requirements was "Excellent knowledge of C++."

Now, I know this somehow implies as expert knowledge of C++, but where exactly does expert knowledge fit into. Is it the knowledge and experience of (let's say) eight years of programming in the language, having and knowing the ins and outs of a specific domain. Or, is it a more brush-up, surface approach to one or more domains and a at the same time a more detailed understanding of the whole language?

For example, you cannot be an expert at writing system drivers and game engines at the same time. So, where does this excellent or expert knowledge fit into?

答:
How good is an excellent football player?
It depends on what kind of level you are looking at, international, children's league etc.

An excellent knowledge of C++ probably means that you should know all of the key words and when they are used along with the STL.

Sometimes it will also include design patters and boost but sometimes it will include none of the above and will require that you pass their coding exam and impress their interviewer.

Honestly there simply is no actual definition.  Do you feel like you can write a complex, multi threaded, multi tiered application employing C++ and some peripheral libraries (STL, MFC, boost etc).  If the answer is yes then you probably have a shot at expert level positions.

If the answer is no you might be wasting your time.

Title: Excellent knowledge of C++


答:
DI does not require invasive Inversion of Control containers or mocking frameworks. You can decouple the code and allow DI via a simple design. You can do unit testing via the built in Visual Studio capabilities.

To be fair, your coworkers have a point. Using those libraries badly (and since they're unfamiliar with them, there will be learning pains) will cause problems. In the end, code matters. Don't screw up your product for your tests.

Just remember that compromise is necessary in these scenarios.

Title: Dependency injection: How to sell it


问:
Are external configuration files considered an antipattern?
Many times I have been in a situation where an application is apparently broken, only to find that an external configuration file has been at fault. Typically this is because the wrong file is there, or that it contains incorrect data.

Is there a better way to allow an external user/process to modify the runtime characteristics of an application, or is this the best known solution to the problem?

I'd like to see discussion on the general case rather than focusing on, say, Unix /etc  or Java JNDI and so on.

答:
On my opinion: NO, external configuration files are not an antipattern.

It is just a technique an architectual pattern to manage software complexity.

In the age of SOLID design principles you have moved software complexity from Monolithic_application to more independent modules that have to be plugged together.

the alternative to "external configuration files" would be to configure modules directly by code.


答:
Most applications will require some external configuration; you can hide this by making it dependent on magic variables, or by saving it to some internal location, but that won't remove the need. The goal is to recognize what should be external, and what can be internal. Only the internal parts can be tested.

An application should not trust an external configuration file to be correct. It should check the correctness, and report errors. If it is not possible for the application to check the configuration file, you are probably doing too much with it. If the configuration file changes the behavior of the application, it shouldn't be external in my opinion.

For example, a database username/password can be easily verified by the application by trying to connect to the database. If this fails, it can report it, and it is obviously not a bug in the application code. Similarly, for a file path the existence and access rights can be checked.

Now, if you were to put SQL queries in the configuration file, then the application cannot easily check the correctness of those queries. The same goes for a full dependency-injection specification (a la Java-Spring XML) file. Those should not be in external configuration files.

But if the specified configuration describes something external, and you can quickly check its correctness, I don't think there is anything wrong with external configuration files.

Edit: also make sure your error reports show which configuration file is used. Nothing is more frustrating than finding out you were looking at the wrong file after hours of trying to find out what's wrong with it.

Title: Are external configuration files considered an antipattern?

Body:
Many times I have been in a situation where an application is apparently broken, only to find that an external configuration file has been at fault. Typically this is because the wrong file is there, or that it contains incorrect data.

Is there a better way to allow an external user/process to modify the runtime characteristics of an application, or is this the best known solution to the problem?

I'd like to see discussion on the general case rather than focusing on, say, Unix /etc  or Java JNDI and so on.


答:
Whether you write unit tests where possible or write small applications involving the code you are modifying, you will have to look at, understand, and then document the logic.

If the code works mostly -- sounds like it does -- then I would preserve the style of the code formatting for that module, whether it's your style or not. It keeps things uniform. However, good comments never go out of style.

I advise a test system and test platform, where you can modify and test this code, without breaking production.

If you can remove elements of the code into a library, I would do it, unless you are working on a library.

Over time, once you understand the logic, you can rewrite and test.

This advice is gated by the language you're using, the ability to get a test bed, and other constraints  you have.

Title: Working on someone else's code


问:
What are requirements for a successful SOA?
I’m an EA in an organisation with 10000+ employees. Strategically we are heading towards SOA. Currently I’m researching about SOA’s and creating a road map and I have come over many blogs that talk about “SOA is dead”. We can all agree that SOA is not just web-services.

The problem is that I have hard to find any information on the reason behind SOA-fail stories in enterprises. What went bad and what went right?

My question is: What are common SOA mistakes in enterprises that make SOA fail in long term? Is the any best practice for SOA? What are the most important requirements for a successful SOA in an enterprise?

It would be good feedback towards our SOA strategy in this organisation.

I have tried to narrow down the question, but it’s hard due to the nature of the question.

答:
From my experience with SOA strategy the biggest issue is making it understandable to business and the governance of it. The limitations are not technological. Typically when designing a SOA architecture you have to be client (those that will consume your services) agnostic. However typically the business analyst and end users only understand the screens that they interact with. So your challenge is to make your services generic enough that many screens in different clients with different workflows can use it. This is tough. e.g. We have a core enterprise service that is used by an internal desktop client and a public facing web application. The same service is reused by both but designing such services are challenging as they present the same data differently and have different workflow.

You also have to watch for dependencies. The project for desktop client may request a change to a service that may be breaking for the web client s well and that project may not be willing to pay to make the necessary changes for the  web client. This requires a real solid governance structure.

The other thing to consider is the granularity of web methods (CRUD style or document style), service Independence etc.
From technical perspective hosting, deployment, service versioining,  security policies, interoperability (e.g. for us Java - WCF), monitoring etc. all needs to be thought about as well.


答:
External configuration files are NOT an anti-pattern. Like everything else they can be used well or poorly depending on the system in question.

You seem to have run into some apps where the external config can break the app without telling the user what's going on. That's bad, but it's not the fault of the config files, it's the fault of whoever decided which parts are in the config files and which parts are in the app, and how to handle errors among them.


答: The adage that is always worked for me is you can't get nine women to make a baby in one month.  </p>

Title: Why does adding more people to a late project make it later?

Body: It's a fairly common adage that adding more programmers to a late project will make matters worse. Why is this?</p>


答:
One thing that I haven't really seen touched on here - don't work on an island.

Unless you are the only programmer at your outfit, there is bound to be somebody that has more experience than you, and quite possibly many people that you can lean on.

Ask questions.  Lots of them.

Don't worry about "annoying" somebody else (within reason) - I'd rather somebody interrupted me for a question or two during a normal development cycle, than having to put out a fire in a production environment later on.

When you are ready to check something in, review it with your mentor(s).  They should be able to tell you not only if something will break something else, but more importantly, why.  Reviewing code will also make the mentor a better programmer, giving him/her a view into the system that they may not otherwise look at as often.

Remember - you are not only learning the system as any new employee would need to do, but you are also learning how to become a programmer.

And five years on, encourage the next New Guy to use you as a mentor.

Title: Working on someone else's code


答: I would classify them more as a "known problem area" than an antipattern.  Unless you are going to deploy a fixed configuration, you'll have to store configuration information somewhere.  I usually like to store most of my configuration information in the database, but you still have to store the database connection information somewhere.  I do prefer the Java/Spring approach of storing the configuration information in the application structure itself, rather than (say) in the user's home directory or the Windows registry, but that's just personal preference.


答:
Don't use DI. Forget it.

Create an implementation of the GoF factory pattern that "creates" or "finds" your particular dependencies and passes them in to your object and leave it at that, but don't call it DI and don't create a complex generalised framework. Keep it simple and relevant. Ensure the dependencies and your classes are such that a switch to DI is possible; but keep the factory the master and keep it extremely limited in scope.

In time, you can hope that it will grow and even one day transition to DI. Let the leads arrive at the conclusion on their own time and do not push. Even if you never get to that, at least your code has some of the advantages of DI, for example, unit testable code.

Title: Dependency injection: How to sell it


答: Do you work with these people on any smaller projects, or just one big one?  It's easier to convince people to try something new on a secondary/tertiary project than the team/companies bread and butter.  The main reasons are that if it fails the cost of removing/replacing it is much smaller, and it's much less work to get it everywhere in a small project.  In a large existing one you either have a large upfront cost to make the change everywhere at once, or an extended period in which the code is a mixture of the old/new approach adding friction because you have to remember which way each class is designed to work.</p>

Title: Dependency injection: How to sell it


问:
Automatically delete files after they expire
I've got this idea for some time and I was wondering if anyone has seen such a feature/app in any operating system and if you haven't, what do you think about it. Where do you think I should begin?

The idea is simple. I think we all have those files that are made and probably used for a few days and then are left on our disk and we never delete them or even check to see if we need them again. It'd be cool if you could right click on a file and click on "Expire in.. 3 days" for example. And the file gets deleted after 3 days. I have a great need for this and maybe some people will find it useful.

I was thinking of writing a script and use the Nautilus Action project in GNOME for a start.

答:
I suppose people that run servers or other space constrained systems run scheduled batch jobs to check for files that need to be deleted.

The IBM MVS operating system (now z/OS) has the ability to automatically delete expired data sets.


问:
Who was the first programmer?
Is there some consensus among historians on who was the first programmer ever? If so, who was it and what were they programming on?

I find it more interesting to know more about the pioneers of programming, regardless if they programmed on a programmable machine or if they've designed the machine themselves to do some computing task.

答:
Augusta Ada King, Countess of Lovelace (1815 - 1852) is credited by most as the first programmer.

The first program was an algorithm to calculate Bernoulli numbers for Charles Babbage's Analytical Engine, and it appeared in her translation notes of Luigi Menabrea's memoir "Sketch of the Analytical Engine Invented by Charles Babbage", more specifically Note G. That said, the math necessary for calculating Bernoulli numbers were known long before Ada's time, however Ada's algorithm is the first instance of a calculating algorithm designed to be executed by a (at the time still hypothetical) machine.

Konrad Zuse (1910 – 1995) is also a solid candidate for the "first programmer" moniker, having invented a floating point binary mechanical calculator with limited programmability, the Z1 (1936) but more importantly the Z3 (1941), a Turing complete electro-mechanical computer.

When it comes to electronic computers, the Atanasoff–Berry Computer (conceived in 1937, operational by 1942) is credited as the first electronic digital computing device, so it's reasonable to think of its designers, John Vincent Atanasoff and Clifford Berry as programming pioneers. The Atanasoff–Berry Computer wasn't programmable though, the first programmable electronic computer was ENIAC (1946).

Although ENIAC's designers John Mauchly and J. Presper Eckert probably did a fair share of programming, most of ENIAC's programming were done by these lovely ladies:

Their names from left to right are Kathy Kleiman1, Jean Bartik, Marlyn Meltzer, Kay Mauchly Antonelli and Betty Holberton at the front. Two of the ENIAC's female programmers, Fran Bilas and Ruth Lichterman, are missing from the photo.

When it comes to digital computers, the first one was Colossus (operational by December 1943), and the project's lead Tommy Flowers (1905 – 1998) should also be considered a programming pioneer, along with Max Newman (1897 – 1984) who was responsible for formulating the requirements for the machine and of course Alan Turing (1912 – 1954), who had designed Bletchley Park's earlier electromechanical cryptanalytical machine, the Bombe (1939), and was influential in Colossus design2.

1 Kathy Kleiman is the founder of the ENIAC Programmers Project and obviously not an ENIAC programmer (too young :)

2 A History of Computing in the Twentieth Century: The Colossus - B. Randell, Newcastle University (PDF)

Title: Who was the first programmer?


答: I've done similar things several times in the past, always with a daemon or cron job.  I haven't seen (or at least noticed) any file systems that support an explicit expiry date, I always had to go on the last-accessed time.  It's simple enough to have a cron job that simply executes find $search_path -atime +3 -exec rm {} \;, but there are lots of ways you could improve on that.

Title: Automatically delete files after they expire

Body:
I've got this idea for some time and I was wondering if anyone has seen such a feature/app in any operating system and if you haven't, what do you think about it. Where do you think I should begin?

The idea is simple. I think we all have those files that are made and probably used for a few days and then are left on our disk and we never delete them or even check to see if we need them again. It'd be cool if you could right click on a file and click on "Expire in.. 3 days" for example. And the file gets deleted after 3 days. I have a great need for this and maybe some people will find it useful.

I was thinking of writing a script and use the Nautilus Action project in GNOME for a start.


答:
When it comes to debugging code, remember: there's always a reason. When you've been trying to find and fix the same stupid bug for a few days and you aren't making any progress, it's tempting to start thinking one or more of:

I'm just not smart enough to figure out how this code works

The guy who wrote this code had no idea what he was doing

Magic is involved: very black magic

Those are all forms of giving up. The antidote is to always remember that computers are deterministic: there's always a reason for what they do. The code may smell like low tide at a fish cannery and resemble a giant bowl of linguine, but by being relentlessly rational and keeping an open mind, you'll figure it out.

Title: Working on someone else's code


答: An excellent C++ programmer knows when to use the myriad of 'features' the language offers and when not to.</p>

Title: Excellent knowledge of C++

Body:
I recently saw a recruiting page for a software company where one of the requirements was "Excellent knowledge of C++."

Now, I know this somehow implies as expert knowledge of C++, but where exactly does expert knowledge fit into. Is it the knowledge and experience of (let's say) eight years of programming in the language, having and knowing the ins and outs of a specific domain. Or, is it a more brush-up, surface approach to one or more domains and a at the same time a more detailed understanding of the whole language?

For example, you cannot be an expert at writing system drivers and game engines at the same time. So, where does this excellent or expert knowledge fit into?


答:
Archimedes could also qualify

Since he is tentatively credited with the creation of the Antikythera mechanism (an example of an early analog computer) some 2000 years ago, at some point he must have made the decision to calculate a particular event.

That act could be thought of as a program, thus he became a programmer.

Title: Who was the first programmer?

Body:
Is there some consensus among historians on who was the first programmer ever? If so, who was it and what were they programming on?

I find it more interesting to know more about the pioneers of programming, regardless if they programmed on a programmable machine or if they've designed the machine themselves to do some computing task.


问:
Is it safe to download VS11/.NET4.5 beta and still deploy to servers with .NET 4.0?
I've been wanting to try out VS2011 and .NET 4.5 beta, but the upgrade path is confusing at best. If I understand what I've read, the .NET 4.5 framework overwrites the .NET 4.0 libraries on your local machine, so libraries such as mscorlib.dll and System.dll will be replaced with the 4.5 version - fully backward compatible, but still different.

If I'm developing ASP.NET sites with VS2011, and assuming I don't use any of the new 4.5 features in the code, do you know of any issues I might have by deploying to a web server with only the .NET 4.0 framework? I wouldn't expect any problems since it's the same CLR, but I'd like to know for sure before I do it.

There's always the option of keeping a separate virtual dev machine for 2011/4.5 so that I can develop on 4.5, but go back to my original 4.0 machine to compile and publish, but I'd rather not go that route if I don't have to.

Thanks

答: It's not 100% backward compatible. Installing 4.5 will prevent StructureMap from working even on a 4.0 project. See this Connect issue for details.</p>


答:
Of course, Inversion of control (IoC) has a great number of benefits:  it simplifies the code, adds some magic that is doing the typical tasks, etc.

However:

It adds a lot of dependencies. Simple hello world application written with Spring can weight a dozen of MB, and I've seen Spring added only to avoid a few lines of constructor and setters.

It adds the abovementioned magic, which is hard to understand for the outsiders (for example, GUI developers that needs to make some changes in business layer). See the great article Innovative Minds Don’t Think Alike - New York Times, which describes how this effect is underestimated by the experts.

It hardens to trace the usage of classes. IDEs like Eclipse has great abilities to track usages of given classes or method invocations. But this trace is lost when there's dependency injection and reflection invoked.

The IoC usage normally doesn't end with injecting dependencies, it ends with countless proxies, and you get stack trace counting hundreds of lines, 90% of which are proxies and invokes via reflection. It greatly complicates stack trace analysing.

So, myself being a great fan of Spring and IoC, I've recently had to rethink the questions above. Some of my collegues are web developers taken inside the Java world from the Web world ruled by Python and PHP and the obvious for javaist things are anything than obvious for them. Some of my other collegues are doing tricks (of course undocumented) which makes the error very difficult to find. Of course IoC misusage makes things lighter for them ;)

My advice, if you'll force usage of IoC in your job, you'll be made responsible for any misusage anyone else will make ;)

Title: Dependency injection: How to sell it


问:
What do you do with a heisenbug?
I've gotten a bug report from one of my users in a section of the software. The scenario is basically a databinding scenario where the user enters info, and that info is printed to pdf.

The problem is, that the functionality:

Is used frequently (about 40 times a week)

Hasn't been updated/modified in months

The area of code is relatively simple to walk through

The validation appears fine (ie, if the information wasn't filled out in the app, validation fires indicating it with a msgbox before the pdf is generated)

But this one user claims that in the past 2 weeks it's happened about 3 times out of 50 and I just can't reproduce it.

So what do you do in the case of a heisenbug?

答:
depending on your situation you might have success with:

Monitor the user's machine (perfmon, eventlog, etc)

Monitor the user (sit with them until they have the issue again)

Replace the user's machine temporarily (get them on another desktop to see if it is a hardware/os thing)

kasterma's suggestion of logging is still good, give them a debug build or use injectable logging if the full deploy is too troublesome.

Title: What do you do with a heisenbug?


答:
If anything, moving configuration from logic to data is preferred. It allows you to make the application more flexible without the need to rework your code.
Missing data files is more a case of too little documentation or sloppy work when installing than a bad practice in terms of coding IMHO.</p>


问:
Is XHTML5 dead or is it just an synonym of HTML5?
So what happened to XHTML5?

http://www.w3.org/TR/html5/

That page is a draft for both xhtml5 and html5?
So there's no difference between these doctypes?

答:
In 2012 at the moment of writing, it was clear that W3C decided to abandon XHTML for HTML 5. This decision was motivated by several reasons:

Only few people were really interested in XHTML. Most of the websites were written in plain HTML.

Even fewer really understood what XHTML is about and how to use it. Too many websites which pretended to serve XHTML used wrong headers, instead of Content-Type: application/xhtml+xml.

Even when you fully understand what XHTML is and what must be the headers, the thing is really tricky with some crappy browsers not accepting/supporting application/xhtml+xml content type. This meant that you had to change the header according to the browser.

The XML part of XHTML also caused some weird situations the developers had to solve. One is INVALID_STATE_ERR: DOM Exception 11 message appearing when you assign the text containing HTML characters (like é) to an element within the XHTML page. When you encounter this error with its very helpful message in a large web application after doing an AJAX request, you have really no idea if it's the fault of JQuery, AJAX, or something else.

Writing HTML 5 code doesn't mean mixing up tags all around. If you're passionate about XML and XHTML, you can still write HTML 5 code which will look very close to XML.

In the early days of mobile phones, XHTML was interesting for the mobile devices which were not very powerful. Parsing XML is much easier than HTML. Now, with dual-core mobile devices, it really doesn't matter if they have to parse clean valid XML or dirty HTML full of hacks and mixed tags.

The spec of October 2014 mentions XHTML syntax. For the moment, it is unclear whether there is such a thing as the new XHTML language (not syntax), and if there is, what will be the position of XHTML, nor the adoption of the new XHTML standard by the mainstream browsers.

Body:
In 2012 at the moment of writing, it was clear that W3C decided to abandon XHTML for HTML 5. This decision was motivated by several reasons:

Only few people were really interested in XHTML. Most of the websites were written in plain HTML.

Even fewer really understood what XHTML is about and how to use it. Too many websites which pretended to serve XHTML used wrong headers, instead of Content-Type: application/xhtml+xml.

Even when you fully understand what XHTML is and what must be the headers, the thing is really tricky with some crappy browsers not accepting/supporting application/xhtml+xml content type. This meant that you had to change the header according to the browser.

The XML part of XHTML also caused some weird situations the developers had to solve. One is INVALID_STATE_ERR: DOM Exception 11 message appearing when you assign the text containing HTML characters (like &eacute;) to an element within the XHTML page. When you encounter this error with its very helpful message in a large web application after doing an AJAX request, you have really no idea if it's the fault of JQuery, AJAX, or something else.

Writing HTML 5 code doesn't mean mixing up tags all around. If you're passionate about XML and XHTML, you can still write HTML 5 code which will look very close to XML.

In the early days of mobile phones, XHTML was interesting for the mobile devices which were not very powerful. Parsing XML is much easier than HTML. Now, with dual-core mobile devices, it really doesn't matter if they have to parse clean valid XML or dirty HTML full of hacks and mixed tags.

The spec of October 2014 mentions XHTML syntax. For the moment, it is unclear whether there is such a thing as the new XHTML language (not syntax), and if there is, what will be the position of XHTML, nor the adoption of the new XHTML standard by the mainstream browsers.


答:
You could add the option to right-click on a file and set the expiration time via a preset list of (1 day, 2 day, 3day, 4day, 5day, 1 week, 2weeks, 1month, X days). After someone adds the expiration time you should have it stored in a file (ex: C:\Program Files\Files Expire\files_to_expire.dat) and have the format of (added time_stamp, expire_time, file location).

Then set up something that will cycle through and read that file every few hours as instantaneous would not be required.

You can also have the files moved to a directory and compressed instead of deleting and allow a GUI to go back to old files and retrieve them upon request. You can also set a max space or time of the old files folder and it will delete them permanently eventually.


答: Try to use some code analyzer tools to find unused code which can be deleted - so at least you do not have to worry about this code. </p>

Title: Working on someone else's code


答: The best thing to do is to add logging and try to catch it in the act.  If that is impractical, then the only thing left is to do a very thorough code review.  Going through the change log would be a reasonable way to begin.</p>

Title: What do you do with a heisenbug?

Body:
I've gotten a bug report from one of my users in a section of the software. The scenario is basically a databinding scenario where the user enters info, and that info is printed to pdf.

The problem is, that the functionality:

Is used frequently (about 40 times a week)

Hasn't been updated/modified in months

The area of code is relatively simple to walk through

The validation appears fine (ie, if the information wasn't filled out in the app, validation fires indicating it with a msgbox before the pdf is generated)

But this one user claims that in the past 2 weeks it's happened about 3 times out of 50 and I just can't reproduce it.

So what do you do in the case of a heisenbug?


答:
Where do you think I should begin?

Begin by writing down a set of use cases that describe all the different ways you can envision for people to use file expiration. Also write down the risks (automatic destruction of evidence, security concerns, etc.).

Next, figure out how the feature should work. How will you keep track of the file expiration date? Is there any way to get an expired file back, or will it really be deleted? Would it be better to have the file system simply hide expired files and only delete them when the space is needed? Developing a detailed understanding of the feature's behavior now will save you a lot of time and effort later.

The next step is to design the feature. Creating some sort of design document will help you stay on track and remember what you're doing even when life intervenes at some point and you have to step away from the project for a few days or weeks. It'll also help you explain the project to others in the future. It doesn't have to be beautiful, but try to capture as many of the decisions that you've made and the reasons behind them as you can -- what's obvious to you today won't be in a few months.

Once you have a design, you can get down to implementing it. Depending on your style, that might mean that you first write a set of tests, or jump right in and start work on the feature itself... but that really gets away from the scope of your question.


问:
What is the point of using the private access modifier for C# class members?
From MSDN...

The access level for class members and struct members, including nested classes and structs, is private by default.

If class members are private by default then why use the private access modifier for them? I see it all the time in code examples and open source projects including the ASP.NET MVC source. I even use it in my own projects but I'm left wondering why.

答: Making them private explicitly makes the code more clear, since now you don't have to depend on developers knowing the default visibility in C#. This could thrown some developers off, so it's better to just be explicit and clear. For example, the default visibility in Java is package, not private, so this might throw off ex-Java programmers.


答:
Because explicitness should be favored over implicitness.

Always writing it also makes you think about what visibility the member should be, leading to fewer bugs due to overlooking it.

Title: What is the point of using the private access modifier for C# class members?

Body:
From MSDN...

The access level for class members and struct members, including nested classes and structs, is private by default.

If class members are private by default then why use the private access modifier for them? I see it all the time in code examples and open source projects including the ASP.NET MVC source. I even use it in my own projects but I'm left wondering why.


问:
Just getting started in Spring and my preference is XML config over annotations. Correct or not?
After having read through some of the Spring docs my inclination is towards using a XML config file rather than annotations on the classes themselves. My reasoning is that by doing so you avoid tying your POJOs to a particular framework.

Based on your experience with Spring, are there any advantages that XML configuration have over an annotation based configuration, and if not what are the disadvantages?

答:
Many of the Spring annotations are now standardized (e.g. CDI for dependency injection), so you're not at all tying yourself to Spring by using them. And for those that aren't: your application won't work without the functionality, will it? So it's basically tied to Spring, whether or not you try to hide that fact.

Annotations are much better for maintainability because they're placed with the code they apply to, so you see them when reading the code. And they require less duplication of logic because what class they apply to is implicit in their placement, whereas XML config files always need to list the class name.

Most people prefer annotations nowadays for these reasons.


问:
Is it bad coding practice to create something in a get if it does not exist?
So I have a webservice that has something like a getAccount where it would return an identifier to the account if it got it, else throw an exception. The client will always want to create an account if an exception is thrown with the same info the get is done with.

I am creating a convenience library for clients that will be handling all of the webservice calls inside so they don't need to know how to do the calls themselves.

What I am wondering is in this library if I were to create a getAccount(accountName) that will get the account if it exists, and if it does not then create it and return the info, is that a bad thing to do? Should I leave it to the client to handle the exceptions or simply name it something like getOrCreateAccount? Does it matter?

Is it bad practice to create something in a get operation?

答: If getAccount() can always return an account, then from the caller's point of view, the account does exist, and has always existed.  There is no need to for getAccount() to 'create' anything.  The account doesn't have to be stored anywhere until it is different from the default account.


答:
Don't dwell over the semantics of "excellent", just apply for the job if it seems interesting and you feel up to it. Let the employer decide whether you're "excellent" enough or not.

An "excellent programmer" knows the raw power of the tool and in the light of it judges several factors that determine implementation of the immediate problem at hand, those factors being: simplicity of implementation, extensibility/reusability, efficiency.

Title: Excellent knowledge of C++


问:
how to nicely use constant std::string in c++
In my current code project, there is an awful lot of constant strings I use to print out error messages.

Hardcoding such strings is generally considered to be bad practice.
Now I'm searching for a "clean way" to include these strings in my program. Therefore I've written a "constants.h" and "constants.cpp" which looks something like

```<code>#ifndef CONSTANTS_H_
#define CONSTANTS_H_

extern std::string error_message_1;

#endif
</code>```

and the constants.cpp:

```<code>#include "constants.h"

std::string error_message_1 = "this is just a sample, not my actual naming convention. move on the the question ;-)"
</code>```

So you might see the problem I have with this: due to a lot of error messages, the variable name itself is fairly long. The error message is even longer, so it crashes the standard 80 characters in one line of code.

Obviously I want my code nice and clean. I don't like going far beyond the 80 charactes per line of code. I don't like somthing like the following either:

```<code>std::string error_message_1 = "this is just a sample about how to"
                              " have one string across many lines"
                              " in the source code. this is not "
                              "very pretty too..";
std::string msg = "and suddenly there's one line which is good..";
std::string error_message_with_longer_name = "and it's even "
                                             "uglier with not "
                                             "equally long "
                                             "variable names";
</code>```

Storing the strings in an external file which one would read in at the start of the program does not seem to be optimal too since the compiler cannot warn about missing strings. Basically this would be a mess to maintain.

So what do you do about it? Is there such a nice thing as "Resources", which I know of Android (or is it Java in general?) development?

Note: Please do NOT tell me that my naming convention is bad. The above is just an example. It's not what it looks like ;-)

答:
Hardcoding strings is fine as long as the values never need to change.
I have seen them stored as static consts and referred to be an associated enum many times.

You could wrap it in a class if you wanted to make the interface easier.

However, there are not really things built into the language to do this - this would be something you did using the language.


问:
How to solve installation errors reported by users, on Android?
I've some application on the Google Play, free to download, but I have some people reporting things like:

"There has been problem installing on my htc x."

How do  I help these people? I could reply and ask things like their android version and what not, but this won't really help me debug it, since the error occurs on installation!

Any general ideas on how to handle this? Maybe some tips about general android installation issues, or on how to help the people?

答:
One thing you could do is ask your user to download a logCat app from android (for example aLogCat, which is open source), then try to install your app, then send you the resulting log. </p>

<p>Based on this log you could investigate why your app is not installed. </p>

Body:
One thing you could do is ask your user to download a logCat app from android (for example aLogCat, which is open source), then try to install your app, then send you the resulting log.

Based on this log you could investigate why your app is not installed.


问:
Was classical BASIC ever used for commercial software development, and if so, how were limitations overcome?
Many of us, including me, started their programming life with programs written on home computers, something like

```<code>10 PRINT "ENTER RADIUS"
20 INPUT R
30 PRINT "CIRCUMFERENCE="; 2 * R * PI
40 PRINT "AGAIN?"
50 INPUT A$
60 IF A$="Y" THEN GOTO 10
70 END
</code>```

Of course, the line-number based BASIC was prone for creating spagetti code, also because most BASIC dialects missed structural statements like WHILE, doing everything but the FOR-loop with IF, GOTO and GOSUB. I'm talking about BASIC dialects before 1991, when QBASIC and Visual Basic appeared.

While BASIC dialects may have promoted bad style amongst aspiring programmers, were there larger commercial projects created in such a BASIC dialect? If so, how did they manage to live with and workaround the obvious shortcomings?

By "serious", I mean:

Not a game (I know some commercial games were written in BASIC, for example, Pimania)

Not freeware

Not trivial, that is, reasonably large (say: at least 1500 LOC)

Sold to several customers (not an in-house development)

"Mission critical" is a plus

答:
BBC BASIC originated on the BBC Micro, released in the UK in 1981. By the time it reached version five, as implemented on Acorn's ARM-based RISC OS computers, it was considered the fastest interpreted BASIC in the world. Its syntax was advanced for its time, including structural keywords like CASE and WHILE and functions and procedures. (It even included an assembler, originally for 6502, and then for ARM in the RISC OS versions.)

Many commercial desktop applications were written using it, perhaps largely because it provided convenient access to the SWI calls that the cooperative WIMP system used. It was fast enough that there were even some arcade games written using it -- Nevryon, an R-Type clone, is one I particularly remember looking at the source of.


问:
What are the roles of singletons, abstract classes and interfaces?
I am studying OOP in C++ and, even though I am aware of the definitions of these 3 concepts, I cannot really realize when or how to use it.

Let's use this class for the example:

```<code>class Person{
    private:
             string name;
             int age;
    public:
             Person(string p1, int p2){this->name=p1; this->age=p2;}
             ~Person(){}

             void set_name (string parameter){this->name=parameter;}
             void set_age (int parameter){this->age=parameter;}

             string get_name (){return this->name;}
             int get_age (){return this->age;}

             };
</code>```

1.Singleton

HOW does the restriction of the class to have only one object work?

CAN you design a class that would have ONLY 2 instances? Or maybe 3?

WHEN is using a singleton recommended/necessary? Is it good practice?

2.Abstract Class

As far as i know, if there's only one pure virtual function, the class becomes abstract.
So, adding

```<code>virtual void print ()=0;
</code>```

would do it, right?

WHY would you need a class whose object is not required?

3.Interface

If an interface is an abstract class in which all the methods are pure virtual functions, then

WHAT is the main difference between the 2 of them?

Thanks in advance!

答:
In the animal kingdom there are various animals which are mammals.
Here mammal is a base class and various animals derive from it.

Have you ever seen a mammal walking by?
Yes, many times I am sure - however they were all types of mammal weren't they?

You have never seen something that was literally just a mammal.  They were all types of mammal.

The class mammal is required to define various characteristics and groups but it does not exist as a physical entity.

Therefore it is an abstract base class.

How do mammals move?  Do they walk, swim, fly etc?

There is no way to know at the mammal level but all mammals must move somehow (let us say that this is a biological law to make the example easier).

Therefore MoveAround() is a virtual function as every mammal who derives from this class needs to be able to implement it differently.

However, being as every mammal MUST define MoveAround because all mammals must move and it is impossible to do it at the mammal level.  It must be implemented by all child classes but there it has no meaning in the base class.

Therefore MoveAround is a pure virtual function.

If you have an entire class that allows activity but is not able to define at the top level how it should be done then all of the functions are pure virtual and this is an interface.

For example - if we have a game where you will code a robot and submit it to me to fight in a battle ground I need to know the function names and prototypes to call.  I do not care how you implement it on your side as long as the 'interface' is clear.  Therefore I can provide you with an interface class which you will derive from to write your killer robot.


问:
Working on someone else's code
I have hardly a year's experience in coding. After I started working, most of the time I would be working on someone else's code, either adding new features over the existing ones or modifying the existing features. The guy who has written the actual code doesn't work in my company any more. I am having a hard time understanding his code and doing my tasks. Whenever I tried modifying the code, I have in some way messed with the working features. What all should I keep in mind, while working over someone else's code?</p>

答: Make sure you're using a program that helps you finding stuff in the current file. Nothing is worse than knowing the thing you're looking for is in the current file, but you scroll and scroll and can't find it. An outline view in the tool you use to edit the code really helps with that problem.</p>

Title: Working on someone else's code


答:
First, look at your organization.  Depending on the experience and capacity to learn new things, Spring XML abstracts logic and functionality by removing the visual dependency chain from your Java files.  If your development team is not accustomed to this type of development model, it can be a steep learning curve.  Don't underestimate this point.  I made this mistake with a group of very sharp developers and was surprised by the amount of overhead it added to the team.

I have found that using Spring Annotations, or any Java Annotations for that matter, offered significant development overhead reductions.  This was due to the direct visual link they provided and seamless integration with your favorite IDEs.  Having the ability to use current day-to-day tools in your development cycle like drilling down into source code, setting debugging break points, Javadoc tool-tips, etc, is not something to take for granted.

Now I know you can get a Spring Tool set for Eclipse, not sure of the others, but you are again adding a another layer of learning on your team.

Title: Just getting started in Spring and my preference is XML config over annotations. Correct or not?

Body:
After having read through some of the Spring docs my inclination is towards using a XML config file rather than annotations on the classes themselves. My reasoning is that by doing so you avoid tying your POJOs to a particular framework.

Based on your experience with Spring, are there any advantages that XML configuration have over an annotation based configuration, and if not what are the disadvantages?


答:
You probably do want to ask them what device, Android version, rooted or not, etc, they are trying to install on and at the very least log it to look for trends. If there's some particular device (or set of devices with particular features), you may eventually spot the pattern.

This shouldn't preclude other efforts, but it's definitely a first step toward figuring things out.

Title: How to solve installation errors reported by users, on Android?

Body:
I've some application on the Google Play, free to download, but I have some people reporting things like:

"There has been problem installing on my htc x."

How do  I help these people? I could reply and ask things like their android version and what not, but this won't really help me debug it, since the error occurs on installation!

Any general ideas on how to handle this? Maybe some tips about general android installation issues, or on how to help the people?


问:
Software Optimization vs. Hardware Optimization - what has the bigger impact?
I was wondering how software optimization and hardware optimization compare when it comes to the impact they have on speed and performance gains of computers.

I have heard that improving software efficiency and algorithms over the years has made huge performance gains. Obviously both are extremely important, but what has made the bigger impact in the last 10, 20 or 30 years?

And how do hardware changes affect the software changes? How much of software optimization is a direct result of hardware improvements and how much is independent of the hardware?

To be clear, I am asking about software optimizations at the level of compilers and operating systems. Obviously using better high level-algorithms will result in the largest speed ups (think: quick-sort vs. bubble-sort), but this question is about the underlying reason why computers are faster today, in general.

答:
I have heard that improving software efficiency and algorithms over the years has made
  huge performance gains

I think what you have heard here is related to better algorithms, but that is what you explicitly excluded from your question.

At the level of operating systems, I don't think many applications run faster today than 10 years ago because the OS has improved (in most cases the opposite is true - most OSs getting bigger and bigger each year, producing more overhead). Only exception may be better support for multiple processors and parallel computing, but that cannot be seen independent of hardware improvements.

For compilers, there have been some improvements of the decades, but the ones with the most impact on performance were the improvements to support features of new hardware. IMHO parallel computing features (multicore, SIMD etc.) and 64 bit processing are the most important things here to mention. EDIT: there is one aspect where improvements in compiler software has increased application performance by around an order of magnitude in the last 10-20 years: just-in-time compilers, especially the ones for Java (since ~1999), and later Javascript.

So it comes mainly down to hardware. In terms of 20 or 30 years ago, it was mainly the processor clock speed, where the increasement correlated roughly 1:1 in application performance for a lot of applications (that's not perfectly true, the real increasement was less since application performance depends also on other hardware components like memory access speed, hard drive speed, GPU speed etc). When you think about the last 10 years, processor clock speed did not increase much more, since processor vendors came to  practical manufacturing limits. Instead, there was a paradigm shift to parallel computing. Multi-core processor, GPU computing (which is also a form of parallel computing), SIMD in the mainstream etc. have dominated the last decade.


答:
Make your favorite SCM tool do double-duty as a CM tool: Put your config files in the repository. To change the config, commit the changes and let your automated deployment tools push them out to production (after running a range of automated tests, of course!)

Et Voila! you have a record of all configuration changes, plus the additional safety net of an automated CI/test system!

As has been pointed out before, architecture & design patterns are not limited to the product-system itself, but also extend to the team/process/systems that help to produce it.


答:
Just create a cron job to delete every file in the global tmp folder of your system if it is older than 14 or 30 days (it is important to have a special folder for this, where it is transparent for everyone that the lifetime of the files living there is limited). If someone wants a file not to be deleted automatically, he just should not save it in the tmp folder.

This was standard on the UNIX systems I had to work on more than 20 years ago. Since there were several users that time, all working on one machine using dumb terminals, and storage was expensive those times, automatic clean-up was very important to keep the system running.


答:
Alpha Software's early DOS database products (circa 1985) "Database Manager I", "Database Manager II" (DMB2) and "Alpha Three" were written in BASIC and compiled with the IBM BASIC compiler.  I worked on "Alpha Three".  All the UI was in BASIC but it had a core TSR (terminate and stay resident) component written in C and ASM that the BASIC communicated with via interrupts.  Line numbers and line breaks took up valuable segment space so code was horribly squished and unreadable. We used shared variables and swapped modules constantly.  It was hard to make work. We still tried to be logical about organization however so our string library was all in the low 60000 line numbers.  A common operation like trimming a string would look like:

$S=$INS;GOSUB 60210;$INS=$S;

We converted to all C shortly after the release of "Alpha Three".

Title: Was classical BASIC ever used for commercial software development, and if so, how were limitations overcome?

Body:
Many of us, including me, started their programming life with programs written on home computers, something like

```<code>10 PRINT "ENTER RADIUS"
20 INPUT R
30 PRINT "CIRCUMFERENCE="; 2 * R * PI
40 PRINT "AGAIN?"
50 INPUT A$
60 IF A$="Y" THEN GOTO 10
70 END
</code>```

Of course, the line-number based BASIC was prone for creating spagetti code, also because most BASIC dialects missed structural statements like WHILE, doing everything but the FOR-loop with IF, GOTO and GOSUB. I'm talking about BASIC dialects before 1991, when QBASIC and Visual Basic appeared.

While BASIC dialects may have promoted bad style amongst aspiring programmers, were there larger commercial projects created in such a BASIC dialect? If so, how did they manage to live with and workaround the obvious shortcomings?

By "serious", I mean:

Not a game (I know some commercial games were written in BASIC, for example, Pimania)

Not freeware

Not trivial, that is, reasonably large (say: at least 1500 LOC)

Sold to several customers (not an in-house development)

"Mission critical" is a plus


答:
Most micros only had basic (ROM) or assembler development tools. For non-speed-critical programs BASIC was used for many commercial applications as well as most in-house company projects. Even when CP/M came along the only real enhancements were the ability to handle bigger projects and use Microsoft's basic compiler (BASCOM). My own experience with early micro development was as follows:

~1980 - Microsoft ROM basic on a Nascom 2 with a little assembler. Commercial application development included a VAT (sales tax) return program and a process control program (both in BASIC).

198? - Still using BASIC, but I now also had Pascal (BLS - precursor to Borland Pascal).

Mid 1980s - PCs begin to dominate and first C compilers appeared (Hisoft and Mix). BASIC goes into decline (revived later in zombie form of course by MS with Visual Basic). GW-BASIC was very popular as an in-house development tool. Numerous commercial packages (accounting, stock control, etc.) was still written in BASIC.

Late 1980s - C becomes the main development language (after MSC 5 released 1986?). Microsoft and Borland dominate for next few years...


问:
What's the difference between Entry Level/Jr/Sr developers?
Other than title and pay, what is the difference?

What different responsibilities do they have.

How knowledgeable/experienced are they?

What is the basic measure to determine where a developer fits into this basic structure?

答: Really, I think it just comes down to how long you have been on the job. If you have 10 years experience you are a senior dev, if you are a graduate then you are probably entry level. I have seen many 'senior' dev's who could hardly code and didn't really know what they were doing and many junior dev's who were fantastic. </p>


答:
The old xBase database scripting languages (as in dBase II, dBase III+, Clipper, etc.) were quite closely related to the various non-standard BASICs of the time.

Not exactly BASIC being used for commercial work, but maybe close enough.


问:
Dependency injection: How to sell it
Let it be known that I am a big fan of dependency injection (DI) and automated testing. I could talk all day about it.

Background

Recently, our team just got this big project that is to built from scratch. It is a strategic application with complex business requirements. Of course, I wanted it to be nice and clean, which for me meant: maintainable and testable. So I wanted to use DI.

Resistance

The problem was in our team, DI is taboo. It has been brought up a few times, but the gods do not approve. But that did not discourage me.

My Move

This may sound weird but third-party libraries are usually not approved by our architect team (think: "thou shalt not speak of Unity, Ninject, NHibernate, Moq or NUnit, lest I cut your finger"). So instead of using an established DI container, I wrote an extremely simple container. It basically wired up all your dependencies on startup, injects any dependencies (constructor/property) and disposed any disposable objects at the end of the web request. It was extremely lightweight and just did what we needed. And then I asked them to review it.

The Response

Well, to make it short. I was met with heavy resistance. The main argument was, "We don't need to add this layer of complexity to an already complex project". Also, "It's not like we will be plugging in different implementations of components". And "We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit".

Finally, My Question

How would you handle my situation? I am not good in presenting my ideas, and I would like to know how people would present their argument.

Of course, I am assuming that like me, you prefer to use DI. If you don't agree, please do say why so I can see the other side of the coin. It would be really interesting to see the point of view of someone who disagrees.

Update

Thank you for everyone's answers. It really puts things into perspective. It's nice enough to have another set of eyes to give you feedback, fifteen is really awesome! This are really great answers and helped me see the issue from different sides, but I can only choose one answer, so I will just pick the top voted one. Thanks everyone for taking the time to answer.

I have decided that it is probably not the best time to implement DI, and we are not ready for it. Instead, I will concentrate my efforts on making the design testable and attempt to present automated unit testing. I am aware that writing tests is additional overhead and if ever it is decided that the additional overhead is not worth it, personally I would still see it as a win situation since the design is still testable. And if ever testing or DI is a choice in future, the design can easily handle it.

答:
Be careful adding extra features (like DI) to a project when not approved. If you have a project plan with time limits you could fall into a trap of not having enough time to finish the approved features.

Even if you don't use DI now, get involved in the testing so you know exactly what the expectations for testing at your company are. There will be another project and you will be able to contrast the issues with testing of the current project vs. DI.

If you don't use DI, you can get creative and make your code DI-"ready". Use a parameterless constructor to call other constructors:

```<code>MyClassConstructor()
{
    MyClassConstructor(new Dependency)
    Property = New Dependent Property
}

MyClassConstructor(Dependency)
{
    _Dependency = Dependency
}
</code>```

Title: Dependency injection: How to sell it

Body:
Be careful adding extra features (like DI) to a project when not approved. If you have a project plan with time limits you could fall into a trap of not having enough time to finish the approved features.

Even if you don't use DI now, get involved in the testing so you know exactly what the expectations for testing at your company are. There will be another project and you will be able to contrast the issues with testing of the current project vs. DI.

If you don't use DI, you can get creative and make your code DI-"ready". Use a parameterless constructor to call other constructors:

MyClassConstructor()
{
    MyClassConstructor(new Dependency)
    Property = New Dependent Property
}

MyClassConstructor(Dependency)
{
    _Dependency = Dependency
}


问:
Who was the first software engineer?
It's fairly well known who the first programmer was but who was or were the first software engineer(s)? By software engineer I mean someone who uses formalized specifications and methods to deliver software not just a batch programming job. When was the term first used?</p>

答:
From NATO's Software Engineering report in 1968:

In the Autumn of 1967 the Science Committee established a Study Group on Computer Science.
  ...
  In late 1967 the Study Group recommended the
  holding of a working conference on Software Engineering. The phrase 'software engineering' was deliberately chosen
  as being provocative, in implying the need for software manufacture to be based on the types of theoretical foundations and practical disciplines, that are traditional in the established branches of engineering.

This implies that there were software professionals beforehand, but the job title didn't appear until the late 1960's.

Title: Who was the first software engineer?


答: There was a lot of commercial software written using BASIC-PLUS on the PDP-11 systems. I remember seeing statistical analysis and accounting packages, plus a fair amount of high-end laboratory automation stuff (I am not sure how "commercial" those were. They tended to be included as part of an instrument package, so I don't know if they were sold separately.). ISTR BASIC was one of the primary languages for HP 2000 application development as well, and it was the primary (possibly only) language supported for their early HP 9800-series workstations.


答:
I believe that the original Ultima on the Apple ][ was written in Applesoft Basic.

DEC used its version of BASIC for much of RSTS and other OSes it developed.