问:
Should you keep a copy of all the code you write?
I know the company you work for owns the code and obviously you will get arrested if you try to sell it. But is it uncommon for developers to keep a personal copy of the code they wrote (for future reference)?

Apparently this guy was sent to prison for copying source code.

答:
This is a very bad idea. That code doesn't belong to you (legally speaking) and having possession of it can get you into a lot of trouble. This becomes even more true when you move to a new job and still keep that source code around. Even worse if it's a competitor. Your company would not be happy if you had access to their source code when you don't work for them anymore.

It's all about managing your risk. It's obviously expected that you retain things from a previous employer that you can use somewhere else. This is why they make your sign non-compete clauses that last X months/years after you leave them, however having possession of the code makes you more vulnerable to someone accusing you of blatantly copying the company's code (even if you didn't, and just used the same ideas). Is having the code worth managing this risk?

Surely the useful stuff you got from writing the code is not the exact syntax; it's the knowledge you gained. It's probably not worth dealing with all this legal stuff.


问:
Is it any good to use binary arithmetic in a C++ code like "C style"?
I like the fact that the C language lets you use binary arithmetic in an explicit way in your code, sometimes the use of the binary arithmetic can also give you a little edge in terms of performance; but since I started studying C++ i can't really tell how much i have seen the explicit use of something like that in a C++ code, something like a pointer to pointer structure or an instruction for jumping to a specific index value through the binary arithmetic.

Is the binary arithmetic still important and relevant in the C++ world?
How i can optimize my arithmetic and/or an access to a specific index?
What about the C++ and the way in which the bits are arranged according to the standard?

... or i have taken a look at the wrong coding conventions ... ?

答:
for example the shift operator << or >>, which is a quick way to
  calculate "something times 2" or "something divided by 2"

Whether you're working in C or C++, write what you mean. Write foo = foo * 2; or foo *= 2; if that's what you mean, not foo = foo << 1;. Let the compiler take care of finding the fastest instruction to use and don't confuse the people who have to read your code with unnecessary hand optimization.

ContentLicense: CC BY-SA 3.0


答:
I always keep a copy of the code I write and take it between jobs. Subsequent employers never get to see/run the code, but I use it as a reference at home: 'Ah yes, didn't I do something similar to that on Project X?'.

Is this legal? Depends on jurisdiction and circumstances, but it is fairly common. Morally, I have no problem with it, providing you aren't simply giving code to new employers... It's a reminder and a demonstration of what you have done, rather than a free resource for your employer.

[The flip side of this is the inevitable shame that comes along when you look at older code: 'What was I thinking?? Why on earth did I do it that way??']

Title: Should you keep a copy of all the code you write?

Body:
I know the company you work for owns the code and obviously you will get arrested if you try to sell it. But is it uncommon for developers to keep a personal copy of the code they wrote (for future reference)?

Apparently this guy was sent to prison for copying source code.


答:
It's not uncommon.

I have a copy of almost1 every piece of code I've written professionally, and certainly all the code from my current projects, regardless of who wrote it2. Along with the code I have a huge pile of legal paperwork clearly defining what I can and cannot do with it. Just having the code is not the same as trying to profit from the code.

That said, it's a legal issue, and legal issues tend to be extremely complicated and localized. If in doubt, you really need to talk to a lawyer. I may keep my code around, but I'm 99% certain I won't get in trouble for doing so.

1 What's missing is mostly what I didn't care to archive. Only one small project's code is missing because of legal reasons.

2 Nature of the projects and my role in them, I'm one of the guys that need to have at least an idea of what goes where, even if I wasn't involved in building a specific module.


问:
Who should be the architect in an agile project?
We are developing the agile way for a few months now and I have some troubles understanding the agile manifesto as interpreted by my colleagues. The project we are developing is a framework for future projects and will be reused many times in the next years.

Code is only written to fulfill the needs of the current user story. The product owner tells us what to do, but not how to do it. What would be right, in my opinion, because he is not implicitly a programmer.
The project advanced and in my eyes it messed up a little bit.
After I recognized an assembly that was responsible for 3 concerns (IoC-Container, communication layer and project internal things), I tried to address this to my colleagues.
They answered that this would be the result of applying YAGNI, because know one told them to respect that functionalities have to be split up in different assemblies for further use.

In my opinion no one has to tell us that we should respect the Separation of Concerns principle. On the other side, they mentioned to prefer YAGNI over SoC because it is less effort to implement and therefore faster and cheaper.
We had changing requirements a lot at the beginning of the project and ended up in endless refactoring sessions, because to much has to be adapted.

Is it better to make such rather simple design decisions up front, even there is no need in the current situation, or do we have to change a lot in the later progress of the project?

答:
Is it better to make such rather simple design decisions up front,
  even there is no need in the current situation, or do we have to
  change a lot in the later progress of the project?

Delay architectural decisions until as late as possible (but no later). You are going to know more about the problem in the future than you do right now, and thereby likely come up with smarter decisions.

For instance, imagine you are trying to decide up front whether to use MongoDB, some other NoSQL or traditional SQL for a project. Delay the decision: write a simple repository layer that will simply save the data in memory, or save data to a JSON file for now, and continue on. Eventually you'll have to replace this stub with something - but later on, you might know with more of a certainty which way to go: "hey, all of this really is a great fit for a document store" or "you know, SQL transactions would really help".

Its important to do this in conjunction with the concept of prioritizing the riskiest parts of your application to be developed first - that is, the parts you understand the least you should do before you do other work. This should mean you end up with an architecture that fits your solution, instead of forcing your solution later to fit in to your pre-selected architecture.

I don't mean to suggest that every project start with an exhaustive comparison of every possible web framework, storage technology, and so on. Hopefully in most projects you can simply default to reliable frameworks that have been used in the past under guidance from the team architect. I'm suggesting that this technique of delaying architectural decisions should be used when you are faced with a decision to which you don't know the answer.

One way to look at it - in an Agile project, you're always doing architecture, instead of trying to do the architecture "up front". If a pair of programmers (you are pair programming right?) picks up a story and realizes that it requires an architectural discussion, they should have it. If they feel they should involve more devs, then they should do that. If this results in a desire to remove some technical debt caused by previous lack of architecture or previous poor architectural decisions, what we've done is had the devs write up a work item for this and work with the product owner to schedule it in. Generally, explaining it in terms of ROI: "we believe the removal of this technical debt will result in the following return", generally in terms of faster response times, or shorter future development cycles.

Also, as a commenter pointed out:

The project we are developing is a framework for future projects and
  will be reused many times in the next years.

This does not sound agile at all. Are you sure your business requirements demand this sort of thing?  Agile is all about recognizing that change happens - this week's great idea is next week's "bottom of the backlog". What technique in future prediction is leading you to be certain about what things will be important to you in three months, much less 'the next few years'?

As far as the original question "who should be the architect in an agile project", I've always selected the most experienced programmer on the team or the programmer that knows the code base the best, and given them the architect title. Sometimes the architect is just letting the developers come up with a solution and guiding the process a little bit, sometimes they are making the call. In teams organized this way, the architect is contributing code to the project most of the time, and playing the "architect" role whenever required.


问:
Designing a hierarchical structure with lots of reads and writes?
I am in the process of working on a video on demand system part of it involves the management of a hierarchical tree structure (think windows explorer) which allows users to upload videos, move folders around, create new folders etc. User action will be allowed depending on which permissions they have.

In addition to managing the structure (creating folders and uploading videos), subscribers will be viewing content (read access). The number of reads will be significantly more than the writes.

My question (and it is big one) is should I store the data in a database (for the writes) and also have some sort of cache which will be used for the reads? or do I use two databases? or is there a better solution?

Also I will have to resolve concurrency issues which I think optimistic locking on the database will resolve.

I have a fair bit about CQRS over the last few months but not sure if this is the way to go.

Any ideas?

答: I'd do the simplest possible thing that would work, which (for me) would be to keep everything in a database.  I'd probably store the media outside the database, just to reduce the load on the connection pool (transferring several GB of data can tie up a DB connection for a long time), but other than that just keep it simple.  Write every configuration change to the database, re-read the configuration every time the UI needs to be updated, get all the features working then profile it to get some numbers.  You may find out it's "fast enough" as it stands, so you don't need to change anything.  If it is slow, you'll be able to quantify how slow it is and where, so you can start optimizing the parts that really matter as opposed to the things you suspect matter.  It's also nice to have a baseline implementation you can test against, so you can verify that your performance improvements haven't broken anything.


答:
But is it uncommon for developers to keep a personal copy of the code
  they wrote (for future reference)?

I don't know how common it is, but common or not, it's still a bad idea.

Programmers often operate in the mindset that solving the same problem twice is a waste of time. We try to design our code to be reusable (sometimes). We build libraries of classes and functions to reuse at some point in the future. We sometimes even give our code away so that nobody else will ever have to write code to solve the same problem that we just did. So it may be understandable to want to take "your" code with you when you move from one job to another. But you still shouldn't do it, for the following reasons:

It's not your code to take.

The code you wrote for your former employer is part of the business they built. Their code is part of their competitive advantage. Sure, competitors could write their own code to solve the same problem, but they shouldn't get the advantage of building on work that your employer paid for, owns, and didn't authorize you to take.

If they have any sense at all, your new employer doesn't want any part of the code that you took from your former employer. The more you "refer" to work you did for some previous employer, the more you put your new employer in legal jeopardy.

If you ever accidentally let it slip at New Employer that you've still got a copy of the stuff you did for Old Employer, your boss at New will probably realize that you'll take a copy of their code when you leave for some other job. That might not sit well with him or her.

Even if you're not cribbing actual lines or just vague ideas from your old stuff, just having your old stuff in your possession could raise suspicions that you might be using it for something. Imagine that Old Employer sues New Employer, and as one of a small handful of employees that moved from Old to New, you suddenly find yourself giving a deposition. None of you actually copied Old's code into New's product, but the lawyer in front of you asks: "Mr. SuperFoo, do you now or have you at any time since leaving Old Employer had in your possession a copy of any code that you or anyone else wrote while working at Old Employer?"

You don't need the code that you wrote last month, last year, or longer ago. You solved the problem once, and now you know how to solve the problem again. Or, you may know how not to solve the problem -- your new implementation will be better because you have experience.

There are better ways. It's hard to go back and learn anything useful by reading old code out of context. A diary or journal that describes what you learn, ideas that you have, etc. is far more useful later on.

Even if Old Employer knows that you've got their code and is OK with that, you still don't want it! The only thing that can come of having it is a 3am phone call: "Hey there, SuperFoo? How are you doing? Listen, you've got a copy of our stuff, right? Look, we've got a problem with the system, and we've narrowed it down to a couple files that you wrote that our new guy just doesn't understand. I know it's late, but could you walk him through SuperDuper.pl?"

Let it go. You don't need it.


问:
Fix bugs, or wait for the customer to find them?
Do other people fix bugs when they see them, or do they wait until there's crashes/data loss/people die before fixing it?

Example 1

```<code> Customer customer = null;
 ...
 customer.Save();
</code>```

The code is clearly wrong, and there's no way around it - it's calling a method on a null reference. It happens to not crash because Save happens to not access any instance data; so it's just like calling a static function. But any small change anywhere can suddenly cause broken code that doesn't crash: to start crashing.

But, it's also not inconceivable that correcting the code:

```<code>Customer customer = null;
...
customer = new Customer();
try
   ...
   customer.Save();
   ...
finally
   customer.Free();
end;
</code>```

might introduce a crash; one not discovered through unit tests with complete coverage, and manual user testing.

Example 2

```<code>float speed = 0.5 * ((G * mass1 * mass2) / R) * Pow(time, 2);
</code>```

People knowing physics will recognize that it's supposed to be R2 in the denominator.

The code is wrong, it's absolutely wrong. And overestimating the speed will cause the retro-rockets to fire too soon, killing all the occupants of the spacecraft.

But it's also possible perhaps having it over-estimate the speed is masking another issue: the air-bags can't deploy while the shuttle is moving too fast. If we suddenly fix the code:

```<code>float speed = 0.5 * ((G * mass1 * mass2) / Pow(R, 2)) * Pow(time, 2);
</code>```

Now the speed is accurate, and suddenly airbags are deploying when they shouldn't.

Example 3

Here's an example that i had recently, checking if a string contains invalid characters:

```<code>if (StrPos(Address, "PO BOX") >= 0)
{
   //Do something
}
</code>```

What if it turns out there's a bug in the Do something branch? Fixing the obviously incorrect code:

```<code>if (StrPos("PO BOX", Address) >= 0)
{
   //Do something
}
</code>```

Fixes the code, but introduces a bug.

The way I see it there are two possibilities:

fix the code, and get blamed for breaking it

wait for the code to crash, and get blamed for having a bug

What do you politically do?

Example 4 - Today's real world bug

I am constructing an object, but calling the wrong constructor:

```<code>Customer customer = new Customer();
</code>```

Turns out that the "parameterless" constructor is actually an parameterized constructor from  further back in the inheritance chain:

```<code>public Customer(SomeObjectThatNobodyShouldBeUsingDirectly thingy = null)
public Customer(InjectedDependancy depends)
</code>```

Calling it is a mistake, since it bypasses all the subsequent constructors.

I could change the object's lineage to not expose such a dangerous constructor, but now I have to change the code to:

```<code>Customer customer = new Customer(depends);
</code>```

But I can't guarantee that this change won't break anything. Like my Example 1 above, perhaps someone, somewhere, somehow, under some esoteric conditions, depends on the constructed Customer to be invalid and full of junk.

Perhaps the Customer object, now that it is properly constructed will allow some code to run that previously never did, and now I can get a crash.

I can't bet your wife's life on it.

And I can test it from here to Tuesday, I can't swear on your daughter's life that I didn't introduce a regression.

Do I:

Fix the code and get blamed for breaking it? or

Leave the bug, and get blamed when the customer finds it?

答:
Start chipping away at your technical debt as soon as you can.

Your examples definitely look like legacy code, having lots of technical debt and I sense there's the fear of change (BTW, this is not a criticism or a judgment).  Your entire team has to acknowledge that you have this technical debt (so you alone aren't blamed for it) and then you can decide how you're going to deal with it.

In Example 1, if Save() doesn't access any instance data, what customer data does it save exactly?  Start fixing and testing that.

In Example 2, it's easy to cover the speed calculator with tests and ensure that it calculates the result correct in all key examples.

In Example 3, there's danger of bringing dead code back to life.  Should that code be eliminated altogether?  What is the intent of the boolean condition under that if?  Is it to ensure the string contains no invalid characters?  Or to ensure it has "PO BOX" in it?  The sooner you start addressing such questions, the better.

After you have fixed a number of such issues, have a sort of retrospective/post-mortem with your team.  It is important to learn from the experience so that you can reduce your defect injection rate in the future.

ContentLicense: CC BY-SA 2.5


答:
is it uncommon for developers to keep a personal copy of the code they wrote

Answering the question directly, I'll say in my experiences this is uncommon. The exception to this that I have seen is people who do a lot of freelancing and they keep the code on hand for their client's future maintenance and enhancement projects, and I would imagine that this is clearly stated in the contract (though I am not in the habit of reviewing my friends' freelancing contracts, so who knows). People I know who work in larger companies have never admitted to keeping code from former employers.

I know I wouldn't because I can't think of a single situation where it would be useful (not to mention that I'm pretty sure my current employer prohibits such things - I would just have to look up the documents to be certain). The code I've written/fixed is usually so specific to a particular business requirement that I can't imagine it ever coming up again in the future in such a way that it would be easier to re-use the old code than write new code.


问:
Are there any standards for preparing a user manual of electronic device?
Are there any standards for preparing a user manual of electronic device?

I am trying to prepare a manual for a device. However, I could not find any format. If I find, I will take this as guide for me.

If there is no standard, what should be in the manual or what should not be in?

答:
Here's what I'd recommend:

Grab your iPhone's or iPod's box and manual,

Replicate the sections according to your device and content.

(Picking a device closer to your type of device might be a better fit, I just went for an example with probable decent support for such things.)


问:
Mobile Compatibility: traditional website look vs native application ?
I have a question related to mobile compatible websites, I have seen two type of websites

One in which they adopt traditional website look and adjust website according to mobile screen, if they have lot of information which can not be adjust according to screen then they expand the height of page, so that user can scroll the page to see more information...

In the second approach they used native application look means use navigation-bar, tab-bar, tool-bar, scroll-view just like in native applications. Height and width of page adjust according to screen size, if they have more information then they use scroll-view etc...

My question is: which approach is better then other, in which approach you feel more comfortable to use website.

答:
According to the recent trend in mobile development, it is better to make the mobile website  look and feel as the traditional one. There is no need to create a native app if mobile site does not use video/audio intensively.

Of course, mobile website will display only main body/part of the traditional website, while hiding left/right and all additional sections, due to the screen width limitations. In this way, support and maintainability of each(mobile/web) sites will be more manageable with less resources in long run.


问:
How to create a Semantic Network like wordnet based on Wikipedia?
I am an undergraduate student and I have to create a Semantic Network based on Wikipedia. This Semantic Network would be similar to Wordnet(except for it is based on Wikipedia and is concerned with "streams of text/topics" rather than simple words etc.) and I am thinking of using the Wikipedia XML dumps for the purpose.

I guess I need to learn parsing an XML and "some other things" related to NLP and probably Machine Learning, but I am no way sure about anything involved herein after the XML parsing.

Is the starting step: XML dump parsing into text a good idea/step? Any alternatives?

What would be the steps involved after parsing XML into text to create a functional Semantic Network?

What are the things/concepts I should learn in order to do them?

I am not directly asking for book recommendations, but if you have read a book/article that teaches any thing related/helpful, please mention them. This may include a refernce to already existing implementations regarding the subject.

Please correct me if I was wrong somewhere. Thanks!

EDIT: The final product should be like a complete Semantic Network (like Conceptnet or Cyc etc.), So I can't use things like Semantic Mediawiki.

(On a second thought, it seems like I should have asked this question on linguistics and not here... )

答:
Since you mentioned semantic network, you might use semantic mediawiki, I think the process will be to download the database dumps of Wikipedia and adding semantic properties wherever needed.
Also are you aware of the Wikidata project??</p>


答:
I think there needs to be a distinction between a design-pattern and actual code (copying line-by-line)

Writing down some psuedocode something like - this is a great way to lazy load X in Y is one thing. Writing down all the code is something else.


问:
How do functional languages handle a mocking situation when using Interface based design?
Typically in C# I use dependency injection to help with mocking;

```<code>public void UserService
{
  public UserService(IUserQuery userQuery, IUserCommunicator userCommunicator, IUserValidator userValidator)
  {
    UserQuery = userQuery;
    UserValidator = userValidator;
    UserCommunicator = userCommunicator;
  }

  ...

  public UserResponseModel UpdateAUserName(int userId, string userName)
  {
     var result = UserValidator.ValidateUserName(userName)
     if(result.Success)
     {
       var user = UserQuery.GetUserById(userId);
       if(user == null)
       {
          throw new ArgumentException();
          user.UserName = userName;
          UserCommunicator.UpdateUser(user);
       }
     }
     ...
  }

  ...
}

public class WhenGettingAUser
{
  public void AndTheUserDoesNotExistThrowAnException()
  {
     var userQuery = Substitute.For<IUserQuery>();
     userQuery.GetUserById(Arg.Any<int>).Returns(null);
     var userService = new UserService(userQuery);
     AssertionExtensions.ShouldThrow<ArgumentException>(() => userService.GetUserById(-121));
  }
}
</code>```

Now in something like F#: if I don't go down the hybrid path, how would I test workflow situations like above that normally would touch the persistence layer without using Interfaces/Mocks?

I realize that every step above would be tested on its own and would be kept as atomic as possible.  Problem is that at some point they all have to be called in line, and I'll want to make sure everything is called correctly.

答: Typically, I would go about this by writing a function that returns a representation of the action that I want to perform on the external resource rather than performing the operation itself. This way the logic and the act of IO are decoupled and testing is much easier.</p>


答: The same way you do in C#, but instead of passing the mock into the constructor, you pass it to the function itself (or as a part of a parameter passed to the function).</p>

Title: How do functional languages handle a mocking situation when using Interface based design?

Body:
Typically in C# I use dependency injection to help with mocking;

```<code>public void UserService
{
  public UserService(IUserQuery userQuery, IUserCommunicator userCommunicator, IUserValidator userValidator)
  {
    UserQuery = userQuery;
    UserValidator = userValidator;
    UserCommunicator = userCommunicator;
  }

  ...

  public UserResponseModel UpdateAUserName(int userId, string userName)
  {
     var result = UserValidator.ValidateUserName(userName)
     if(result.Success)
     {
       var user = UserQuery.GetUserById(userId);
       if(user == null)
       {
          throw new ArgumentException();
          user.UserName = userName;
          UserCommunicator.UpdateUser(user);
       }
     }
     ...
  }

  ...
}

public class WhenGettingAUser
{
  public void AndTheUserDoesNotExistThrowAnException()
  {
     var userQuery = Substitute.For<IUserQuery>();
     userQuery.GetUserById(Arg.Any<int>).Returns(null);
     var userService = new UserService(userQuery);
     AssertionExtensions.ShouldThrow<ArgumentException>(() => userService.GetUserById(-121));
  }
}
</code>```

Now in something like F#: if I don't go down the hybrid path, how would I test workflow situations like above that normally would touch the persistence layer without using Interfaces/Mocks?

I realize that every step above would be tested on its own and would be kept as atomic as possible.  Problem is that at some point they all have to be called in line, and I'll want to make sure everything is called correctly.


问:
Should I continue my self-taught coding practice or learn how to do coding professionally?
Lately I've been getting professional work, hanging out with other programmers, and making friends in the industry. The only thing is I'm 100% self-taught. It's caused my style to extremely deviate from the style of those that are properly trained. It's the techniques and organization of my code that's different.

It's a mixture of several things I do. I tend to blend several programming paradigms together. Like Functional and OO. I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity. Like a game object. Next I also go the simple route when doing something. When in contrast, it seems like sometimes the code I see from professional programmers is complicated for the sake of it! I use lots of closures. And lastly, I'm not the best commenter. I find it easier just to read through my code than reading the comment. And most cases I just end up reading the code even if there are comments. Plus I've been told that, because of how simply I write my code, it's very easy to read it.

I hear professionally trained programmers go on and on about things like unit tests. Something I've never used before so I haven't even the faintest idea of what they are or how they work. Lots and lots of underscores "_", which aren't really my taste. Most of the techniques I use are straight from me, or a few books I've read. Don't know anything about MVC, I've heard a lot about it though with things like backbone.js. I think it's a way to organize an application. It just confuses me though because by now I've made my own organizational structures.

It's a bit of a pain. I can't use template applications at all when learning something new like with Ubuntu's Quickly. I have trouble understanding code that I can tell is from someone trained. Complete OO programming really leaves a bad taste in my mouth, yet that seems to be what EVERYONE else is strictly using.

It's left me not that confident in the look of my code, or wondering whether I'll cause sparks when joining a company or maybe contributing to open source projects. In fact I'm rather scared of the fact that people will eventually be checking out my code. Is this just something normal any programmer goes through or should I really look to change up my techniques?

答:
When you begin developing applications in cooperation with other developers, some of these personal style foibles are going to get in the way.

If you begin working at a shop that uses underscores, you are going to use underscores.  Everyone, regardless of their previous background, follows the shop standard for coding style.

Unless your coding style is extremely obvious, you'd better get used to writing clear, concise comments explaining how your code works, so that other developers can follow it.

If you don't know anything about unit tests, buy a good book.  There are plenty of good books on unit testing out there.  Same with MVC.

Professional software developers know how to play well with others, without littering the sandbox.  The very best ones know how to read and write code regardless of style.


答:
You don't need to be a greater commenter. But you should be a good commiter (yes, start using some sort of VCS - I recommend Git).

Style is a thing that ALWAYS evolve. Don't worry about it. You'll learn what is a reusable code and what's not. But you have to practice and to get help for it.

Try helping in some Open Source project on Github. Some people are really nice there, and will try to help you. This is the best tip I can give to you.

Title: Should I continue my self-taught coding practice or learn how to do coding professionally?

Body:
Lately I've been getting professional work, hanging out with other programmers, and making friends in the industry. The only thing is I'm 100% self-taught. It's caused my style to extremely deviate from the style of those that are properly trained. It's the techniques and organization of my code that's different.

It's a mixture of several things I do. I tend to blend several programming paradigms together. Like Functional and OO. I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity. Like a game object. Next I also go the simple route when doing something. When in contrast, it seems like sometimes the code I see from professional programmers is complicated for the sake of it! I use lots of closures. And lastly, I'm not the best commenter. I find it easier just to read through my code than reading the comment. And most cases I just end up reading the code even if there are comments. Plus I've been told that, because of how simply I write my code, it's very easy to read it.

I hear professionally trained programmers go on and on about things like unit tests. Something I've never used before so I haven't even the faintest idea of what they are or how they work. Lots and lots of underscores "_", which aren't really my taste. Most of the techniques I use are straight from me, or a few books I've read. Don't know anything about MVC, I've heard a lot about it though with things like backbone.js. I think it's a way to organize an application. It just confuses me though because by now I've made my own organizational structures.

It's a bit of a pain. I can't use template applications at all when learning something new like with Ubuntu's Quickly. I have trouble understanding code that I can tell is from someone trained. Complete OO programming really leaves a bad taste in my mouth, yet that seems to be what EVERYONE else is strictly using.

It's left me not that confident in the look of my code, or wondering whether I'll cause sparks when joining a company or maybe contributing to open source projects. In fact I'm rather scared of the fact that people will eventually be checking out my code. Is this just something normal any programmer goes through or should I really look to change up my techniques?


答:
In fact I'm rather scared of the fact that people will eventually be checking out my code.

Good. Being conscious that people are going to look at your code will make you try harder.

Programming has become an incredibly large field. There are dozens of topics, tools, niches, and specializations, some of which are whole careers unto themselves. There is a vast amount to learn and know, and when you work with other programmers, there will always be stuff you know that they don't and stuff they know that you don't. This is a good thing.

If you are worried that your experience is incomplete, there are plenty of steps you can take to amend that through formal education and collaboration with trained experts. But it sounds like you're afraid there's some quantifiable milestone after which people say "Okay, now that I've mastered that, I'm officially a programmer." There is no such milestone. I've definitely had moments where I thought "yeah, now I'm getting somewhere" after I learned something new, but there's no magic list of things you must know and do to call yourself a programmer.

I know a lot of things about programming, I've used a dozen languages in lots of projects, and yet the subset of programming knowledge I can call my own is tiny. And I like that. Frankly, a programmer isn't something you are. A programmer is something you are constantly learning to be.

Take honesty inventory of your skills, your strengths and weaknesses. Get feedback from people with more experience than you. Look for positions that line up pretty well with where you think you are - but don't be afraid to go for jobs that are a little outside your current mastery. If you only take jobs you already know everything about, you'll never learn at work.


问:
Are too many assertions code smell?
I've really fallen in love with unit testing and TDD - I am test infected.

However, unit testing is normally used for public methods. Sometimes though I do have to test some assumptions-assertions in private methods too, because some of them are "dangerous" and refactoring can't help further. (I know, testing frameworks allow testing private methods).

So it became a habit of mine that the first and the last line of a private method are both assertions.

However, I've noticed that I tend to use assertions in public methods (as well as the private) just "to be sure". Could this be "testing duplication" since the public method assumptions are tested from the outside by the unit testing framework?

Could someone think of too many assertions as a code smell?

答:
Whenever you do not have full control over your input parameters, it is a very good idea to test up front for simple errors.  Fail on null for instance.

This is not duplication of your tests, as they should test that the code fails appropriately given bad input parameters, and then document that.

I do not think you should assert on the return parameters (unless you explicitly have an invariant you want the reader to understand).  This is also the job of the unittests.

Personally I do not like the assertstatement in Java, since they can be turned off and then it is a false security.

Title: Are too many assertions code smell?


问:
Reasons to Use a VM For Development
Background:

I work at a start-up company, where one team uses Virtual Machines to connect to a remote server to do their development, and another team (the team I'm on) uses local IIS/SQL Server 2005/Visual Studio installations to conduct work.

Team VM is located about 1000 miles from Team Non-VM, and the servers the VMs run off of are located near Team VM (Latency, for those that are wondering, is about 50ms).

A person high in the company is pushing for Team Non-VM to use virtual machines for programming, development, and testing.

The latter point we agree on -- we want Virtual Machines to test configurations and various aspects of the web application in a 'clean' state.

The Problem:

What we don't agree on is having developers using RDP to connect to a desktop remotely that contains Visual Studio, SQL Server, and IIS to do the same development we could do locally on our laptops.

I've tried the VM set-up, and besides the color issue, there is a latency issue that is rather noticeable, not to mention that since we're a start-up, a good number of employees work from home on occasion with our work laptops, and this move would cut off the laptops. They'd be turned in.

Reasons to Use Remote VMs for Development (Not Testing!):

Here are the stated reasons that this person wants us to use VMs:

They work for TeamVM.

They keep the source code "safe".

If we want to work from home, we could just use our home PCs.

Licenses (I don't know what the argument is, only that it's been used).

Reasons not to use Remote VMs for Development:

Here are the stated reasons why we don't want to use VMs:

We like working from home. We get a lot done on our own time.

We're not going to use our Home PCs to do work related stuff.

The Latency is noticeable.

Support for the VMs (if they go down, or if we need a new VM) takes a while.

We don't have administrative privileges on the VM, and are unable to change settings as needed.

What I'm looking for from the community is this:

What reasons would you give for not using VMs for development? Keep in mind these are remote VMs -- this isn't a VM running on a local desktop. It's using the laptop (or a desktop) as a thin client for a remote VM. Also, on the other side of the coin:  Is there something we're missing that makes VMs more palatable for development?

Edit: I think 'safe' is used in term of corporate espionage, or more correctly if the Laptop gets stolen, the person who stole would have access to our source code.  The former (as we've pointed out, is always going to be a possibility -- companies stop that with litigation, there isn't a technical solution (so far as I can see)).  The latter point is ( though I don't know its usefulness in a corporate scenario) mitigated by Truecrypt'ing the entire volume.

答:
Since everyone seems to be agreed that latency is a big killer, here's an alternative scenario that espouses some of the actual benefits when you have a server farm in-house to run the VMs with little to no latency:

1) Speed. The server allocates my VM more resources than my laptop has, meaning it compiles faster, runs faster, and my productivity speeds up.

2) Stability. Something broke? Just roll back to the last stable snapshot. Takes about thirty seconds.

3) Consistency. All the VMs are the same, a clone of the environment this code will eventually run on. No weird quirks related to customization of laptops show up when I'm working in the VM.

OwnerDisplayName: George Stocker

Title: Reasons to Use a VM For Development


问:
Security using jsonp
I'm writing an app that will make available a set of api functions that require cross site scripting to work.  I'll be utilizing jsonp which will allow other developers to consume these services for their web applications.

What security concerns should I consider to protect my server data?

What security concerns should other developers take when consuming my services via jsonp?

答:
Actually, if you still have a chance, you should take a look at CORS (Cross-Origin-Resource-Sharing). It is the W3C specification that is intended to replace the JSONP wrapping workaround, and it went into working draft as recent as April 3, 2012.

So my answer to you, in regards to security, is that you should look at CORS.

Here is the W3C Working Draft Security Considerations link, regarding CORS security and the 'replacement' of JSONP.

Title: Security using jsonp


答:
Programming has an art component and a discipline component to it. The art component is in thinking up best approaches and implementing them; the discipline is in making sure that you did it correctly, and that others can understand your code and enhance it when necessary.

The art component is fun: you do it because you enjoy it. Naturally, that is the part that you teach yourself first.

The discipline component is more of a nuisance: you do it out of necessity. It is a vital component of working in a team, though: you cannot get away from doing it, at least to some degree. Once your code is integrated with that of your teammates, your flexibility to "change things at will" takes a nose dive. Yet you need an ability to change your code with confidence in response to changing requirements, or to address bugs. This is where various "boring" tests come in: with lots of tests in place, it is easy to check if your latest change breaks things or not.

Code style gains importance, too, because adhering to a common style makes the code easier to read for everyone. In larger companies you would find nightly jobs that test compliance with the coding standards automatically, and e-mail you nasty warnings when you deviate.

Back to your question, concentrating on the art component is a natural early stage of programmer's development. It can take several years of working in the industry before you start appreciating the discipline component. You do not need to actively look to "changing up your techniques", though: they will morph naturally in the process of working in a team.


答:
To your question, yep you should always be looking to change your technique, to embrace the unique project and emerging technology.

@assfallows's point of "Frankly, a programmer isn't something you are. A programmer is something you are constantly learning to be." is really the be all and end all of coding.

Its great that you are noticing areas where you do something different from others, especially when you see it is a standard. You have spotted Unit Testing and MVC - and now your next step must be to learn about them. See how they work, what you need to implement them and try and get a sense of when it is a good design to implement them.

This is a constantly evolving field with new languages and patterns rising and falling. If you are comfortable with the coding aspect, start examining the design part. Learn what makes them good and when to use them.

Certainly joining a team is a great benefit - you always need other eyes to look at your code to spot areas you rushed or did not think out the full implications.


问:
Is running "milli"-benchmarks a good idea?
I just came across the Caliper project and it looks very nice.
Reading the introduction to microbenchmarks, one gets the feeling that the developers would not suggest to use the framework if the benchmark takes longer than a second or so. I looked at the code and it looks like a RuntimeOutOfRangeException is actually thrown if a scenario takes longer than 10s to execute.

Could you explain to me what the problems are with running larger benchmarks?

My motivation for using Caliper was to compare two join-algorithm implementations. Those will definitely run for quite some time and will do some disk IO, yet running the entire database would make it hard to do the comparison, because the configuration of the algorithms and the visualization of the results would be a pain.

答:
Many code slowdowns occur in small, tight loops.  If you know that's where your time is being spent, a micro-benchmark can help you optimize just that small bit of code.

Unit tests need to complete in a reasonable amount of time.  It's rare indeed for me to write a unit test that takes longer than a second or two to execute, since I might have two or three hundred such tests or more in a test assembly.

OwnerDisplayName: Konstantin Weitz


答:
One idea with test-driven design is to run all your unit tests when building a project, which allows you to catch functional regressions quickly, before committing the changes that caused them.  For this to work, though, all your tests need to complete quickly.

If your benchmarks all run quickly, they can be included in your test framework (I don't know if that is what Caliper is supposed to be for, but Google is heavily into TDD...).  In any case, the whole point of adding benchmarks to your test-driven infrastructure would be to catch major performance regressions quickly -- so, for that kind of usage, you'd want to flag taking too long as an error.

Title: Is running "milli"-benchmarks a good idea?

Body:
I just came across the Caliper project and it looks very nice.
Reading the introduction to microbenchmarks, one gets the feeling that the developers would not suggest to use the framework if the benchmark takes longer than a second or so. I looked at the code and it looks like a RuntimeOutOfRangeException is actually thrown if a scenario takes longer than 10s to execute.

Could you explain to me what the problems are with running larger benchmarks?

My motivation for using Caliper was to compare two join-algorithm implementations. Those will definitely run for quite some time and will do some disk IO, yet running the entire database would make it hard to do the comparison, because the configuration of the algorithms and the visualization of the results would be a pain.


问:
What's the most appropriate duration of the video tutorial?
It is now more and more popular to have video tutorials of the software or technology instead of writing long articles. As for me, it makes perfect sense, especially for such areas like "Getting Started" or "What's New".

What do you think is the most appropriate duration for such a videos? If you record the video tutorial yourself, would you just touch main points to keep it brief, or rather split it into a number of parts to keep the same level of details? And why?

I know this question isn't implied to have one and only answer. I'd like to hear the reasoning behind various opinions.

I have personally come across a video tutorial 45 minutes long today, and I got tired at around minute 10... So, my own impression is it's better to keep it from 5 to 10 minutes to gain visitor's attention fully.

Thanks!

答:
Let's assume for the sake of discussion that you are (or can enlist the services of) an excellent speaker and editor and you're able to cut out all unnecessary material, which is depressingly far from the truth with most tutorial videos and "screencasts" which tend to be full of stumbles and pauses and monotone blathering.

The answer is:

Two and a half minutes.

What's that number based on? I hear you asking.  You just pulled it out of your backside, didn't you?  Well, I'll tell you where I got it from.

Two and a half minutes is the average length of a YouTube movie.

You could not possibly ask for a better pool of data.  We are talking about over 50 billion videos and over 2 billion views per day.  And averaged out of all of these people and all of these videos, the majority are watched for well under 3 minutes, which is only a minute short of the average song length and about the same length as a typical commercial break on TV.

Some studies show that a typical attention span is 10 minutes, but that statistic is for college students in a classroom environment.  That is, they are trying to focus their attention.  Most users who watch your tutorial video are already in the mindset that this video is just a nuisance, it's something that they have to get through in order to start using some other thing that was too complicated and unintuitive to understand without a tutorial video.  They desperately want to get through it as quickly as possible and get back to their "real" work or activities.

Two and a half minutes.  That's it.  More than three minutes and you're going to start losing people.

If you've got a lot of material to get through then split it up over multiple videos.  One concept or task per video.  Do not make people sit through a 10-minute video just to learn a single concept.

Attention spans seem to be declining every year with the advent of services like SMS messaging and now Twitter.  Row against this current at your own peril.


答:
Here's a simple question for you. Go to your boss and tell them: "I have a copy of all code I wrote while I worked here. Only code I wrote, not other peoples. This is for my own education, and I will never give it out".

Their next actions will dictate (yes, that word does exist in North America/World) if you are in the wrong or right in their eyes.

Regardless of your own "ethics", you work for an employer. If they deem that what you are doing is wrong, then it is wrong based on their ethics. As they pay you, and you are employed by them, then it is in your court to either agree with them, or disagree, which could get you fired.

Now it's a question of integrity. I've let a previous employee's take some of our code, but I have vetted all of it first.

Just because you believe you are in the right, does not make you in the right. Usually software developers sign contracts when they are employed. If you signed one, you need to live by your word.


答:
Twitter's Bootstrap is an attempt to provide a boilerplate to help you answer that in one website smoothly. Great concept, but if you already have the site designed, it can be absurd to try and implement.

I tried doing that for mine and gave up after a week...

Title: Mobile Compatibility: traditional website look vs native application ?

Body:
I have a question related to mobile compatible websites, I have seen two type of websites

One in which they adopt traditional website look and adjust website according to mobile screen, if they have lot of information which can not be adjust according to screen then they expand the height of page, so that user can scroll the page to see more information...

In the second approach they used native application look means use navigation-bar, tab-bar, tool-bar, scroll-view just like in native applications. Height and width of page adjust according to screen size, if they have more information then they use scroll-view etc...

My question is: which approach is better then other, in which approach you feel more comfortable to use website.


问:
For nodejs what are best design practices for native modules which share dependencies?
Hypothetical situation, I have 3 node modules all native, A, B, and C.

A is a utilities module which exposes several functions to javascript through the node interface, in addition it declares/defines a rich set of native structures and functions

B is a module which is dependent on data structures and source in A, it exposes some functions to javascript, in addition it declares/defines native structures and functions

C is a module which is dependent on data structures and source in A & B, it exploses some functions to javascript, in addition it declares/defines native structures and functions

So far when setting up these modules I have a preinstall script to install other dependent includes, but in order to access all of another modules source what is the best way to link to it's share library object (*.node) ?

Is there an alternative best practice for native modules (such as installing all source from other modules before building that single module)?
Reply

答:
There are essentially two ways to do this. Which one is suitable for you depends on what you want to accomplish.

Case 1: A, B and C are loosely related, that is if e.g. B can be used without A and C. Having A and/or C available would extend the functionality of B.

Case 2: A, B and C are tightly related and some part of A, B or C relies on the existence of A, B or C. Together they form a logical unit.

If Case 1 fits your projects' purpose, then you want to build separate node modules and have the end user pull in those modules and use them at will.

If Case 2 fits better, then you want to compile A, B and C into one module e.g. ABC. You can still structure the source code (and exported API) of the ABC module according to A, B and C.

Building three separate modules and linking them dynamically makes little sense. In fact, they are dynamically linked (by node) when imported (require'd) in node-land. Linking them together statically might make more sense, bus is essentially just a messier way of accomplishing "solution 2" (producing a single module).

Edit:

If A, B and C are three modules that are not authored by you, then you are dealing with a hierarchy. As you explain it in your hypothesis, the hierarchy of dependance is:

```<code>B --requires--> A
C --requires--> B
C --requires--> A
</code>```

Thus A could be "owned" by B, and B could be owned by C. If you author C, then provide a user-facing API with an entry-point in JavaScript, where you require the three modules. Compile A, B and C as separate modules and have them live "inside" your compound module. The file system structure could look something like this:

```<code>foo/          # Your compound module
foo/index.js  # require('./_A'), require('./_B'), require('./_C')
foo/_A.node
foo/_B.node
foo/_C.node
</code>```

As the code in _C.node requires certain symbols to be implemented (i.e. the depending symbols from A and B), you will need to load the modules in order.

Note that I have not tested this, but in theory, this should work.

Body:
There are essentially two ways to do this. Which one is suitable for you depends on what you want to accomplish.

Case 1: A, B and C are loosely related, that is if e.g. B can be used without A and C. Having A and/or C available would extend the functionality of B.

Case 2: A, B and C are tightly related and some part of A, B or C relies on the existence of A, B or C. Together they form a logical unit.

If Case 1 fits your projects' purpose, then you want to build separate node modules and have the end user pull in those modules and use them at will.

If Case 2 fits better, then you want to compile A, B and C into one module e.g. ABC. You can still structure the source code (and exported API) of the ABC module according to A, B and C.

Building three separate modules and linking them dynamically makes little sense. In fact, they are dynamically linked (by node) when imported (require'd) in node-land. Linking them together statically might make more sense, bus is essentially just a messier way of accomplishing "solution 2" (producing a single module).

Edit:

If A, B and C are three modules that are not authored by you, then you are dealing with a hierarchy. As you explain it in your hypothesis, the hierarchy of dependance is:

B --requires--> A
C --requires--> B
C --requires--> A

Thus A could be "owned" by B, and B could be owned by C. If you author C, then provide a user-facing API with an entry-point in JavaScript, where you require the three modules. Compile A, B and C as separate modules and have them live "inside" your compound module. The file system structure could look something like this:

foo/          # Your compound module
foo/index.js  # require('./_A'), require('./_B'), require('./_C')
foo/_A.node
foo/_B.node
foo/_C.node

As the code in _C.node requires certain symbols to be implemented (i.e. the depending symbols from A and B), you will need to load the modules in order.

Note that I have not tested this, but in theory, this should work.


问:
Why is MaybeChannelBound callable?
The Queue class in the python kombu library inherits from MaybeChannelBound, which in turn implements the call method (making it callable). The call() method itself is a thin wrapper around the bind() method.

It is not clear why this was done, as calling the bind() method seems (to my simple mind, at least) to be clearer and more descriptive of the intent of the function.

Why would somebody use the call() method in a situation like this?

答:
William,

I wrote the code, so I guess I should give an answer ;)

MaybeChannelBound is a common base class for Exchange and Queue,
because they both have the same semantics (terrible name, as so often happens
when one tries to use inheritance...)

The __call__ was an API decision, so:

```<code>queue(channel)
</code>```

returns a queue that is bound to a channel so that you can do operations
on it. I simply thought the call looked better in the API, I don't remember
exactly why I included the .bind method too, but I can guess that

If someone wanted to create a subclass of this, then overriding
a bind operation would seem neater than using __call__.

When duck-typing it would be rather useless to check for __call__ (callable),
and .bind could be used for this purpose.

In recent Kombu you rarely have to bind the channels yourself, e.g.
when publishing a message you now send a list of entities to declare
to Producer.publish instead (and declarations are cached too):

```<code>producer = Producer(connection)
producer.publish(message, retry=True, declare=[queue])
</code>```

where you previously would have to write:

```<code>with connection.channel() as channel:
    queue(channel).declare()
    producer.publish(message)
</code>```

There isn't always any universally good reason for everything I do though,
sometimes I do things just because it is a practice of mine.
Sometimes those practices turns out the useful, other times
they just end up being useless boilerplate.

Title: Why is MaybeChannelBound callable?

Body:
William,

I wrote the code, so I guess I should give an answer ;)

MaybeChannelBound is a common base class for Exchange and Queue,
because they both have the same semantics (terrible name, as so often happens
when one tries to use inheritance...)

The __call__ was an API decision, so:

queue(channel)

returns a queue that is bound to a channel so that you can do operations
on it. I simply thought the call looked better in the API, I don't remember
exactly why I included the .bind method too, but I can guess that

If someone wanted to create a subclass of this, then overriding
a bind operation would seem neater than using __call__.

When duck-typing it would be rather useless to check for __call__ (callable),
and .bind could be used for this purpose.

In recent Kombu you rarely have to bind the channels yourself, e.g.
when publishing a message you now send a list of entities to declare
to Producer.publish instead (and declarations are cached too):

producer = Producer(connection)
producer.publish(message, retry=True, declare=[queue])

where you previously would have to write:

with connection.channel() as channel:
    queue(channel).declare()
    producer.publish(message)

There isn't always any universally good reason for everything I do though,
sometimes I do things just because it is a practice of mine.
Sometimes those practices turns out the useful, other times
they just end up being useless boilerplate.


问:
Should you keep a copy of all the code you write?
I know the company you work for owns the code and obviously you will get arrested if you try to sell it. But is it uncommon for developers to keep a personal copy of the code they wrote (for future reference)?

Apparently this guy was sent to prison for copying source code.

答:
I have just recently deleted all the old code I kept from my previous employer. I only kept pieces of code that I thought were good for future reference. I've actually found that I've moved on considerably since I left and I've never referred to the old code. I've found/discovered/learnt far better ways of solving the same problems.

It was a nice little trip down memory lane though :)


问:
Moving from mock to real objects?
I'm like doing TDD so I started everything mocking objects, creating interface, stubbing, great.

The design seems to work, now I'll implement the stuff, a lot of the code used in the stubs are going to be reused in my real implementation yay!

Now should I duplicate the tests to use the real object implementation (but keeping the mocks object of the sensitive stuff like Database and "services" that are out of my context (http calls, etc...)) Or just change the mocks and stubs of the actual tests to use the real objects.......

So the question is that, keep two tests or replace the stubs, mocks?

And after that, I should keep designing with the mocks, stubs or just go with real objects?

(Just making myself clear I'll keep the mock object of the sensitive stuff like database and services that are out of my context, in both situations.)

EDIT

[Fact]
public void Change_status()
{
    var dbContext = MockRepository.GenerateStub<IDbContext>();
    var repository = MockRepository.GenerateMock<IRepository<Foo>>();

    var predicate = MockRepository.GenerateStub<Func<Foo, bool>>();
    repository.Expect(x => x.Get(predicate)).Return(_foo).Repeat.Once();
    dbContext.Expect(x => x.Commit());

    var ctl = MockRepository.GenerateStub<IFooCtl>();
    ctl.Stub(x => x.RejectRequest(_fooView)).WhenCalled(delegate
    {
        var foo = repository.Get(predicate);
        foo.Status = Status.Rejected;
        _fooView.Status = Status.Rejected.ToString();

    }).Return(true);

    ctl.RejectRequest(_fooView);

    repository.VerifyAllExpectations();
    dbContext.VerifyAllExpectations();
    Assert.True(_fooView.Status == "Rejected");
    Assert.True(result.Count() == 1);
}
```

<p>This is a test, where I mock the repository, context and stub the facade. So what I'm trying to say is if I should change the stub of the facade to use the "real" code so this should be tested as</p>

<pre class="lang-csh prettyprint-override"><code>[Fact]
public void Change_status()
{
    var dbContext = MockRepository.GenerateStub<IDbContext>();
    var repository = MockRepository.GenerateMock<IRepository<Foo>>();

    var predicate = MockRepository.GenerateStub<Func<Foo, bool>>();
    repository.Expect(x => x.Get(predicate)).Return(_foo).Repeat.Once();
    dbContext.Expect(x => x.Commit());

    var ctl = new FooCtl(loanRepository, happyLoanDbContext);
    var result = ctl.RejectRequest(_loanView);

    repository.VerifyAllExpectations();
    dbContext.VerifyAllExpectations();
    Assert.True(_result);
}
</code>```

Or if I should leave everything mocking and stubbing that tests the designs and create new ones that tests the implementation.

EDIT

Thanks for all your answer, I think I understand it better, I must know which is my SUT and test that, no mock or stub the SUT just the components that will help the SUT to pass the test

答:
The idea of TDD is that you concentrate about implementing only one thing at the time. So when implementing a class you discover that you need some external class you should not start implementing that, but simply make a stub or even better just an interface, that has just enough functionality to make the class that you are actually implementing work.

Mocks are used to be sure that you test only one thing. Only one class. So even if you have implemented real classes in place of the stubs/interface you made to temporary cover for some missing functionality, the mocks should always be there to test that class in isolation (part of you automatic test suite). When you move on to implement an actual class instead of the stub, you should also make a mock object to represent the class you started out implementing.

Hope that helps.

Title: Moving from mock to real objects?


问:
Is it any good to use binary arithmetic in a C++ code like "C style"?
I like the fact that the C language lets you use binary arithmetic in an explicit way in your code, sometimes the use of the binary arithmetic can also give you a little edge in terms of performance; but since I started studying C++ i can't really tell how much i have seen the explicit use of something like that in a C++ code, something like a pointer to pointer structure or an instruction for jumping to a specific index value through the binary arithmetic.

Is the binary arithmetic still important and relevant in the C++ world?
How i can optimize my arithmetic and/or an access to a specific index?
What about the C++ and the way in which the bits are arranged according to the standard?

... or i have taken a look at the wrong coding conventions ... ?

答:
As many have mentioned already, be aware — do not to prematurely optimize things. But when you find CPU-bound code that is a bottle neck, one of the best ways to understand which of your alternate implementations would be better, using Clang C/C++ -> LLVM IR is a great idea. If you're more comfortable in a web browser, try http://llvm.org/demo/.

The IR (Intermediate Representation) generated by Clang and LLVM are virtual machine instructions. You can for instance write the same algorithm/arithmetic function in "C style" and "C++ style" (I'm guessing "STL-style"?) and compare the IR generated by the compiler. Even if your end-product compiler isn't based on LLVM, the IR code will be representative of what code is actually generated and compiled. Beyond IR there is only hardware optimizations (like how landing pads from conditional branches are implemented). LLVM can produce target machine assembly, if you think it would make you wiser (but I wouldn't recommend going beyond IR).


答:
It seems to me that you're asking whether you should turn your unit tests into integration tests.  I would say the answer is decidedly no.  I think that you'd be well served to keep the unit tests you're writing (the ones that use mock objects) as the backbone of your test suite.

For the integration tests (where you assemble larger parts of your application with actual objects instead of mocks), I'd have fewer of these, since they are necessarily more time consuming to run and much more involved to maintain.  These are often good as "smoke tests", but I wouldn't have these be the focus of your test suite.

Title: Moving from mock to real objects?

Body:
I'm like doing TDD so I started everything mocking objects, creating interface, stubbing, great.

The design seems to work, now I'll implement the stuff, a lot of the code used in the stubs are going to be reused in my real implementation yay!

Now should I duplicate the tests to use the real object implementation (but keeping the mocks object of the sensitive stuff like Database and "services" that are out of my context (http calls, etc...)) Or just change the mocks and stubs of the actual tests to use the real objects.......

So the question is that, keep two tests or replace the stubs, mocks?

And after that, I should keep designing with the mocks, stubs or just go with real objects?

(Just making myself clear I'll keep the mock object of the sensitive stuff like database and services that are out of my context, in both situations.)

EDIT

[Fact]
public void Change_status()
{
    var dbContext = MockRepository.GenerateStub<IDbContext>();
    var repository = MockRepository.GenerateMock<IRepository<Foo>>();

    var predicate = MockRepository.GenerateStub<Func<Foo, bool>>();
    repository.Expect(x => x.Get(predicate)).Return(_foo).Repeat.Once();
    dbContext.Expect(x => x.Commit());

    var ctl = MockRepository.GenerateStub<IFooCtl>();
    ctl.Stub(x => x.RejectRequest(_fooView)).WhenCalled(delegate
    {
        var foo = repository.Get(predicate);
        foo.Status = Status.Rejected;
        _fooView.Status = Status.Rejected.ToString();

    }).Return(true);

    ctl.RejectRequest(_fooView);

    repository.VerifyAllExpectations();
    dbContext.VerifyAllExpectations();
    Assert.True(_fooView.Status == "Rejected");
    Assert.True(result.Count() == 1);
}
```

<p>This is a test, where I mock the repository, context and stub the facade. So what I'm trying to say is if I should change the stub of the facade to use the "real" code so this should be tested as</p>

<pre class="lang-csh prettyprint-override"><code>[Fact]
public void Change_status()
{
    var dbContext = MockRepository.GenerateStub<IDbContext>();
    var repository = MockRepository.GenerateMock<IRepository<Foo>>();

    var predicate = MockRepository.GenerateStub<Func<Foo, bool>>();
    repository.Expect(x => x.Get(predicate)).Return(_foo).Repeat.Once();
    dbContext.Expect(x => x.Commit());

    var ctl = new FooCtl(loanRepository, happyLoanDbContext);
    var result = ctl.RejectRequest(_loanView);

    repository.VerifyAllExpectations();
    dbContext.VerifyAllExpectations();
    Assert.True(_result);
}
</code>```

Or if I should leave everything mocking and stubbing that tests the designs and create new ones that tests the implementation.

EDIT

Thanks for all your answer, I think I understand it better, I must know which is my SUT and test that, no mock or stub the SUT just the components that will help the SUT to pass the test


答:
Under an employer to employee relationship in most parts of North America it is illegal to transfer or transmit digital material (i.e. source code) from your employers equipment without prior legal authorization from the employer.

Part of the legal laws relating to the definition of an employee in the work place, is the description that the employee does not provide his/her own working equipment unless otherwise stated in the employee contract, with exception to trades which require the employee to purchase their own equipment (i.e. construction worker).

Most employment laws in North America define the employer as the principal risk taker in an employee to employer relationship. The employee is paid for his/her time while the employer provides materials, equipment and controls the work related activities of the employee.

At what time during this relationship does it make it OK to steal valuable material from the employer, who has paid for and taken risk in having said material created?

The key problem with this was the question "source code that you wrote?". No sir, it is not you who wrote it. Under guidance of your employer it is them who wrote it. You are just the hired hand who typed it out. There is no court in North America that will side with you should your employer take legal actions to secure their property. Just copying the source code to a USB thumb drive can get you into hot water.

With that said, if an employer allowed you to use your own equipment (i.e. laptop) or transmit the material, then it's a different matter. The employer must notify you upon termination that any materials should be returned/destroyed.

Just thought I would post this answer, because it seems like some people thought this was a gray area. I really don't think if you're a developer, that you should be going around the Internet posting that you keep copies of employer's materials. I mean, you clearly already knew the answer to this question because you created a new member account just to ask this question. ;)


答:
For a different number of reasons, like working from home, you might as well already have a copy, and I for one wouldn't go deleting these after a job, why do that? It doesn't go against my beliefs or something.

But, regarding using it, it is not so useful as a blog post!

Bottom line: write your code, blog about the problems you've faced and how you solved them (especially when it's generic and broad stuff), and don't mind to keep a (possibly encrypted) souvenir from the last job.


问:
What individual needs to be aware when signing a NDA with client?
I am very new to IT industry and have no prior experience. However I came into contact with a party who is gear to build a mobile application. But, they want me to sign NDA (No Disclosure Agreement).

The definition seems vague,

The following definitions apply in this Agreement: Confidential
  Information means information relating to the online and mobile
  application concepts discussed and that:

(a) is disclosed to the Recipient by or on behalf of XYZ;

(b) is acquired by the Recipient directly or indirectly from XYZ;

(c) is generated by the Recipient (whether alone or with others); or

(d) otherwise comes to the knowledge of the Recipient,

When they say otherwise comes to the knowledge of the recipient. Does it mean if I think of any idea from my own creative mind and which is similar to their idea then it would be a breach of this agreement? and also is it okay to tell to include application name in definition as currently to me it sounds like any online of mobile application concept they think I should not disclose it to anybody. "Confidential Information means information relating to the online and mobile application concepts discussed and that:"

I am more concerned about this part,

Without limiting XYZ’s rights at law, the Recipient agrees to
  indemnify XYZ in respect of all claims, losses, liabilities, costs
  or expenses of any kind incurred directly or indirectly as a result of
  or in connection with a breach by it or any of its officers,
  employees, or consultants of this Agreement.

Is it really common in IT industry to sign this agreement between client and developer? Any particular thing I should be concerned about?

答:
There are number of articles and posts that can give you guidance on where you need to be extremely picky. Here you are some resources:

Wikipedia

5 Pitfalls to Understand About Non-Disclosure Agreements

Pitfalls and Limitations Of The Non-Disclosure Agreement


问:
Taking Object Oriented development to the next level
Can you mention some advanced OO topics or concepts that one should be aware of?

I have been a developer for 2 years now and currently aiming for a certain company that requires a web developer with a minimum experience of 3 years.

I imagine the interview will have the basic object oriented topics like (Abstraction, Polymorphism, Inheritance, Design patterns, UML, Databases and ORMs, SOLID principles, DRY principle, ...etc)

I have these topics covered, but what I'm looking forward to is bringing up topics such as Efferent Coupling, Afferent Coupling, Instability, The law of Demeter, ...etc.

Till few days ago I never knew such concepts existed (maybe because I'm a communication engineer basically not a CS graduate.)

Can you please recommend some more advanced topics concerning object oriented programming?

答:
From initially reading your post I would have said: "you're well prepared". But actually it sound's like Yam has some points there.

I was put in the position to lead a couple of interviews and also be part of the decision process, so I may say you'll be surprised once you sit on the other side of the table, to what extent people tend to misinterpret their situation as a job applicant:

They need YOU - you in contrast have a skill (telling from your writing you haven't been sitting on your hands during that two years) on a rather advanced level that's dearly hunted for by the industry

They are people, too - they need to get at least the imagination that they could work together with you on a daily basis, and you won't get the job if you feel less comfortable and maybe become a shy or more silent version of yourself.

Never be afraid to say straightaway that you don't know something. If you have read across the topic in question even ages ago and know only vaguely what it is, state that clearly. That's of course after being asked for something specific. If there are any any "elephants in the room", such as maybe an undocumented gap in your CV, put the story clear b4 you are asked for it.

Always keep those in mind. I cannot tell which things will get you the job at whatever specific company you are applying at, but i can tell you what kind of guys always got a full thumbs up and a 2nd invitation:

if you're showing in an authentic way that this job IS your passion, that you are BURNING to solve problems of this kind and just get the machines do all this wicked stuff, that you are an open-minded, constantly evolving character which one can also "agree-to-disagree" but still cooperate constructively with, then you have a your foot in the door

bringing along some example of your nicest kung-fu along (nothing academic, something cool or handy that best-relates somehow to what they are doing you can show on the laptop that you'll bring along) can help push them over the edge

research as much as you can about what they do, who their customers are and what currently might be the most prominent project. Find something, just a spark maybe, that really interests you, ASK THEM QUESTIONS. If it's a big corporation, try to understand which exact sector (horizontal) and level (vertical) point of the hierarchy you are applying to join for.

The best thing is: if you manage to follow these - of course depending on the company's size and HR practices - you might not be put into an oral-exams-like situation at all. That is, if the interviewer gets the feeling that you really enjoy understanding and exploring the stuff you do, and that you're not just the Mysql or MongoDb fanboy reciting some features of their favourite "golden Hammer" (see Anti-Patterns) without ever having a clue on the factual backgrounds.

Nobody needs to be a human dictionary of computer science, nowadays we need creators, inventors, problem-solvers.

Of course, all of this just being my personal two cents from that perspective change experience.

P.S. The most ground-breaking readings to me in my career were "Clean Code" by R.C.Martin and "Pragmatic Programmer" (Hunt/Thomas) which managed to restore my will to continuously battle mediocre or "just-good-enough" code and identify and improve suboptimal processes where I see them. Somebody having embraced those books would always immediately shoot to my top candidate list to give the job to.


问:
Why is it good to split a program into multiple classes?
I'm still a student in high school (entering 10th grade), and I have yet to take an actual computer course in school. Everything I've done so far is through books. Those books have taught me concepts such as inheritance, but how does splitting a program into multiple classes help? The books never told me.

I'm asking this mainly because of a recent project. It's an arcade video game, sort of like a Flash game as some people have said (although I have no idea what a Flash game is). The thing is, it's only one class. It works perfectly fine (a little occasional lag however) with just one class. So, I'm just asking how splitting it into multiple classes would help it.

This project was in Java and I am the only person working on it, for the record.

答:
The simplest answer is that if you put everything into one class, you have to worry about everything at once when you're writing new code. This may work for small projects, but for huge applications (we're talking hundreds of thousands of lines), this quickly becomes next to impossible.

To solve this issue, you break up pieces of functionality into their own classes and encapsulate all the logic. Then when you want to work on the class, you don't need to think about what else is going on in the code. You can just focus on that small piece of code. This is invaluable for working efficiently, however it's hard to appreciate without working on applications that are huge.

Of course there are countless other benefits to breaking your code into smaller pieces: the code is more maintainable, more testable, more reusable, etc., but to me the biggest benefit is that it makes massive programs manageable by reducing the amount of code you need to think about at one time.

ContentLicense: CC BY-SA 4.0


问:
Real world T4 usage
How many of you have ever used (or even know of)  the Visual Studio Text Templating Engine?

I mean, T4 templates have been around for quite some years now. The where initially included in Visual Studio 2005 SDK, and they where moved to Visual Studio 2008 core just before releasing it.

What I want to know is if this is really used out there. I mean, why doesn't the VS team invested in a descent minimal editor for the templates? It doesn't even have syntax couloring!
I know there are a couple of good T4 editors out there, but as they don't come built in, I tend to think that this is an unknown feature for most developers.

Have you ever used T4 templates in any of your projects? I'm really interested in answers that explain how they created their own T4 to accelerate, automate, or generate artifacts for your project.

答: A few years ago I was part of a couple of projects where we used T4 templates via the Guidance Automation Toolkit as well as the Smart Client Software Factory.  On both projects we were able to take out most, if not all, of the repetitive setup steps for creating new modules that would work within the main Composite UI App Block shell applications we had created.  The T4 templates we created would ask the developer/user for various pieces of project-specific data and then do everything from initial Visual Studio solution creation to view/controller creation.  I agree with you that editing the templates isn't the easiest thing in the world, but the payoff was always worth it for us.  There were some add-in's if I remember correctly that would add syntax coloring for you too...</p>

Title: Real world T4 usage


答:
Well, the simplest response might be "It helps organize things." If nothing else, you might compare it to sections in a notebook -- it's just plain simpler if you have "all the stuff relating to the UI" over here and "all the stuff relating to the gameplay" over there.

The more sophisticated answer is that divvying up work is not just convenient, but very important to managing complexity (and "managing complexity" is pretty much the name of the game when it comes to programming). Classes, or other types of module, allow you to "separate concerns." Not only do you know where to look for "stuff related to the UI" but you can be sure that if you want to make a change to the UI, you can just make it in the one place, and you don't have to worry "now, is that the only place where I set my font to Comic Sans?". And you can make a change and know that the effect of that change is only to whatever (small) scope is appropriate. If everything is in a single class or module, essentially everything is global, and that makes things very difficult to reason about.

In the specific case of classes as a type of software module, there's also a lot of behavior that is associated with a class, and most developers in the object-oriented paradigm find it very helpful to have meaningful names associated with the classes that group related functions together. So you probably wouldn't actually have a UI class, you'd probably have a Button class. There's a whole body of knowledge and techniques associated with object-oriented class design and it's the most common way of organizing large systems in mainstream programming.

Title: Why is it good to split a program into multiple classes?

Body:
I'm still a student in high school (entering 10th grade), and I have yet to take an actual computer course in school. Everything I've done so far is through books. Those books have taught me concepts such as inheritance, but how does splitting a program into multiple classes help? The books never told me.

I'm asking this mainly because of a recent project. It's an arcade video game, sort of like a Flash game as some people have said (although I have no idea what a Flash game is). The thing is, it's only one class. It works perfectly fine (a little occasional lag however) with just one class. So, I'm just asking how splitting it into multiple classes would help it.

This project was in Java and I am the only person working on it, for the record.


问:
Javascript naming conventions
I am from Java background and am new to JavaScript. I have noticed many JavaScript methods using single character parameter names, such as in the following example.

```<code>doSomething(a,b,c)
</code>```

I don't like it, but a fellow JavaScript developer convinced me that this is done to reduce the file size, noting that JavaScript files have to be transferred to the browser.

Then I found myself talking to another developer. He showed me the way that Firefox will truncate variable names to load the page faster.  Is this a standard practice for web browsers?

What are the best-practice naming conversions that should be followed when programming in JavaScript? Does identifier length matter, and if so, to what extent?

答:
Infuriated by the "clean code developer" philosophy (and given you now know from above posts that with due to minifying the size of your variable names will have zero impact on performance) i could only advise:

Find the best IDE for your personal development needs that has a decent auto-completion and intellisense features, such as aptana, netbeans, eclipse (all free) or any of the numerous commercial products (if i had a free-game, i'd look into JetBrains' products)

Write your code in a manner that makes any commenting superfluous. That means, instead of writing

```<code>getXy(e) { return [e.pageX, e.pageY ] }
</code>```

which could mean really anything (especially in a crazy loosely typed language like js ;) you make the code express itself

```<code>getPageCoordinatesFromEvent(event) {
    return [event.pageX, event.pageY ];
}
</code>```

In a good IDE, you would typically never type any variable name that long twice - seconds time you type a few letters and just press enter from the auto-completion. If you insist on typing every character yourself, a good IDE will anyway notice you of a typo anyway. This is just a very superficial example, therefore i strongly suggest (not as a form of criticism but as an honest recommendation) that you

Get the books "Clean Code" by Robert C.Martin and or "Pragmatic Programmer" by Hunt/Thomas and never ask yourself this kind of questions again - you'll be much too busy working on a continuous integration server to automate the boring test-, & build parts of the development process (including minifying) and concentrate on the fun part, writing clearly understandable code that does great stuff!

P.S. If you need to get up to speed with developing state-of-the-art javascript code, take a peek at John "Mr. jQuery" Resig's book on "Pro Javascript Techniques" right after or together with the above .

Title: Javascript naming conventions

Body:
Infuriated by the "clean code developer" philosophy (and given you now know from above posts that with due to minifying the size of your variable names will have zero impact on performance) i could only advise:

Find the best IDE for your personal development needs that has a decent auto-completion and intellisense features, such as aptana, netbeans, eclipse (all free) or any of the numerous commercial products (if i had a free-game, i'd look into JetBrains' products)

Write your code in a manner that makes any commenting superfluous. That means, instead of writing

getXy(e) { return [e.pageX, e.pageY ] }

which could mean really anything (especially in a crazy loosely typed language like js ;) you make the code express itself

getPageCoordinatesFromEvent(event) {
    return [event.pageX, event.pageY ];
}

In a good IDE, you would typically never type any variable name that long twice - seconds time you type a few letters and just press enter from the auto-completion. If you insist on typing every character yourself, a good IDE will anyway notice you of a typo anyway. This is just a very superficial example, therefore i strongly suggest (not as a form of criticism but as an honest recommendation) that you

Get the books "Clean Code" by Robert C.Martin and or "Pragmatic Programmer" by Hunt/Thomas and never ask yourself this kind of questions again - you'll be much too busy working on a continuous integration server to automate the boring test-, & build parts of the development process (including minifying) and concentrate on the fun part, writing clearly understandable code that does great stuff!

P.S. If you need to get up to speed with developing state-of-the-art javascript code, take a peek at John "Mr. jQuery" Resig's book on "Pro Javascript Techniques" right after or together with the above .


问:
Standards & compliances for secure web application development?
I am working with developers right now that write code the way they want and when i tell them to do it other way they respond that its just matter of preference how to do it and they have their way and i have mine.

I am not talking about the formatting of code, but rather of way site is organized in classes and the way the utilize them. and the way they create functions and process forms etc.

Their coding does not match my standards, but again they argue that its matter of preference and as long as goal achieved the can be different way's to do it. I agree but their way is proven to have bugs and we spend a lot of time going back and forth with them to fix all problems security or functionality, yet they still write same code no matter how many times i asked them to stop doing certain things.

Now i am ready to dismiss them but friend of mine told me that he has same exact problem with freelance developers he work with. So i don't want to trade one bad apple for another.

Question is is there some world wide (or at least europe and usa) accepted standard or compliance on how write secure web based applications. What application architecture should be for maintainable application.

Is there are some general standard that can be used for any language ruby php or java govern security and functionality and quality of code? Or at least for PHP and MySQL i use for my website. So i can make them follow this strict standard and stop making excuses.

答:
There are wide variety of these standards and each BIG Player in software business has it's own guidelines. The approach and methodology on application security may vary or have common aspects depending on chosen development platform. As a good solid start you may look at the following articles for thought:

WEB ARCHITECTURE

Wikipedia - Application security

Design Guidelines for Secure Web Applications

MSDN - Building Secure Web Services


答:
One uses multiple classes because as you get into bigger stuff you'll find there's simply no way you can keep track of everything when it's one big pile of code.

You simply have to divide and conquer to handle it.


答:
Back in the day it was common for developers to have their personal library of routines that they would use to solve problems at the current job.  The source would stay behind when the developer left, but any enhancements also went with him.

This resulted in a win-win situation.  It was also just a subset of all the code written.

Of course most of what was in personal libraries would be in standard libraries today.


答:
In finance the CFA addresses this issue. You are not allowed to take information related to clients or your work for the company (in this case code). But nothing prevents you from memorizing what you can and then writing it down later.

Not sure how legitimate that is, but I think your best bet is to leave your source code but write down your ideas and how you did it as soon as you get home. Stealing is stealing and in court all they are trying to find out to decide is if you copied the code or not.


答:
I see your arrested Chinese man and raise you with a "code is not property, therefore cannot be stolen".

Ref.: Code 'not physical property', court rules in Goldman Sachs espionage case

With that said.

Do I keep code I write? Absolutely.

Do I keep full projects? Absolutely.

Do I make sure I thumb drive my code from my work PC onto a home machine? You betcha!

Do I ever re-use that code at another company or in a personal project. Nope.

Do I often look at old code and go WtF!? All the time.


问:
What is the benefit of a visual editor over straight programming?
I'm trying to figure out what the benefit to having a WYSIWYG HTML editor over hard coding, outside of, say, accessibility.  It seems like a waste of time to learn how to use something like Dreamweaver over Notepad++.  Am I missing something here?  Every time I've ever used one, I end up going back into the code to fix the problems the visual editor made.</p>

答: WYSIWYG editors can be useful for things like building quick tentative designs or for borrowing bits and pieces of code, but actual html coding with intimate knowledge of how to program without a wysiwyg is very necessary to complete advanced work.  Other answers mentioned how necessary it is to use programs with autocompletion and other helpful shortcuts will help you be more efficient.  I personally found Sublime Text 2 to work very well when programming web-pages and even in programming languages like ruby or python.</p>


答:
In effect what you have done is re-invented procedural programming. Mind you it is quite possible to write software that way and the compiler probably won't care. For many years this is how things were done until computers got faster and tools got better.

That being said if you break up your code into different logical units (Classes, modules etc) is that you can have a lot of short easy to understand pieces of code.  that can be maintained later. Many of my modules are less than 20 lines of code. I know that all the code on a given subject is in a specific place. It also means that if someone else joins the project they will have a much easier time finding things.

As Gerald Sussman said our programs should be written first so that people can read it and second so that the computer can run it. (And if you have nto read "Structure and Interpretation of Computer Programs yet you should)


答:
If you are saving your code with the goal of reusing it later, I have two issues with that:

If the code is domain specific, it is probably also proprietary. Anyway, no two businesses or problems are exactly alike and trying to fix one problem with the solution for another is not a good pattern.

If the code you are saving solves a common problem, you should
question your approach. Why are you spending a lot of effort to solve a
common problem when they are likely existing (and better) open source
solutions?

If you believe that you have the best solution to a common problem,
you should really try to share you code publicly on a public repository
and/or code blog when you write it, not keep it to yourself. Your
boss should not object to sharing a generic library or force you to
reinvent the wheel (if he does, find a new job).

If you are saving your code because you want to show it to a potential employer or to improve your skills, I suggest you contribute to an open source project instead.


答:
Sure. I like to keep a copy of all the work I do - whether it's writing code or otherwise. Call it a scrapbook, if you like. Breaking the rules? Perhaps.

The comments about competitive advantage are irrelevant unless your next employer is a direct competitor. If you move from a phone company to a software house, or from a game developer to a database developer, it doesn't matter. If you're actually planning to reuse code - well, that's a different story.

Interestingly, you often hear about web developers bringing a "box of tools" with them, with a standard set of JavaScript libraries and CSS stylesheets. But I haven't seen that mentioned here.


问:
Updating and organizing class diagrams in a growing C++ project
I am working on a C++ project that is getting bigger and bigger. I do a lot of UML so it was not really hard to explain my work to co-workers until now. Lately I implemented a lot of new features and I gave up updating by hand my Dia UML diagrams. My code is documented with Doxygen but the generated doc is not really visual.

I would just like my co-workers to quickly understand updates in my class design. Doxygen seems to handle UML diagrams using Graphviz but I would like to know if other possibilities are available and what you guys do to be as clear as possible when showing your code to co-workers (not clients).

答:
What you are looking for is called round-trip engineering. There are more and less solid tools available for this.

The basic idea of round-trip engineering is this:

You can make a change to the UML diagram in your UML modeling tool, and the change is automatically reflected in a code update (i.e., you add a method to the UML class, and the tool adds the method to the .h and .cpp files as well)

You can make a change to the source code and your UML diagram is updated automatically.

While full-blown round-trip engineering is pretty much an ongoing research effort, there are tools out there, which at least partially support it. In particular, such tools usually support converting existing projects and in that process they allow you to create UML diagrams from the current state of the source.

Hence, instead of manually updating your diagrams, you could re-generate them each time you need to show your progress and only waste a little bit of time for layouting, or selecting relevant parts for your presentation. But in particular, you are guaranteed that the diagrams you shown contain exactly the information present in your source code.

For C++ I'm afraid I only know one such tool: Enterprise Architect. I'm sure there are more around, though.

As a final note: Automation at this level is far from being perfect. You will get a decent UML diagram, but certainly not something like you would have derived by yourself. First off, once you leave the realm of static structure and want behavioral diagrams, most tools are not only at a total loss, but produce totally useless output. And second, even for static structure, it is a difficult subject to derive aggregation/composition/association(classes)/etc. automatically from source code. Given that most code generators are still manually tuned to produce the desired outputs in the obvious UML model -> code direction, it is understandably much more difficult to generalize the reverse direction.