答: One thing I would really recommend for learning quality coding and architecture concerns would be the teachings of "Uncle Bob" (Robert Martin). He has some $1 videos that are nicely bite-sized, if perhaps overly whimsical, as well as some good books.</p>

Title: Involuntarily becoming a programmer: how to do it right?

Body:
My background is electrical engineering, DSP to be more precise. The company I currently work for does a lot of diverse projects, mostly building analog hardware. Being somewhat closer to computers than everybody else around here I'm often the one writing code for both embedded devices (which I'm perfectly fine with) and Windows or Linux OS. It is the latter that is foreign territory to me.

I can code, and I know a few languages (C/C++, Java, some VB.NET), but I only used them for algorithm simulations in signal and image processing, neural networks, and other similar applications. For me programming has been a computational tool more than anything else. However, I get more and more projects where I have to write proper full-fledged software, and I don't really know how to do it, because I never had to do it, and I was never really interested enough. I have myself seen quite a few engineers who got converted into coders to a certain degree because of job demands, and most of them weren't that great at what they did. I'm sure many people have encountered the same.

If I were to learn writing proper software with good user interface, good internal architecture and so on, how do I do it? We don't have anyone at work who could tell me what's good practice and what isn't. Given that I can write code in the rawest sense of the word, what else is there to know about writing good software and how I do I get there on my own?


问:
Involuntarily becoming a programmer: how to do it right?
My background is electrical engineering, DSP to be more precise. The company I currently work for does a lot of diverse projects, mostly building analog hardware. Being somewhat closer to computers than everybody else around here I'm often the one writing code for both embedded devices (which I'm perfectly fine with) and Windows or Linux OS. It is the latter that is foreign territory to me.

I can code, and I know a few languages (C/C++, Java, some VB.NET), but I only used them for algorithm simulations in signal and image processing, neural networks, and other similar applications. For me programming has been a computational tool more than anything else. However, I get more and more projects where I have to write proper full-fledged software, and I don't really know how to do it, because I never had to do it, and I was never really interested enough. I have myself seen quite a few engineers who got converted into coders to a certain degree because of job demands, and most of them weren't that great at what they did. I'm sure many people have encountered the same.

If I were to learn writing proper software with good user interface, good internal architecture and so on, how do I do it? We don't have anyone at work who could tell me what's good practice and what isn't. Given that I can write code in the rawest sense of the word, what else is there to know about writing good software and how I do I get there on my own?

答:
Books:  The main thing is to read (good) books on your language of choice.  Once you know your language of choice, you can get "More Effective X" or "Y best Practices" and so on.  I find cookbooks to be very good at bridging gaps you may have.  So, I guess that is at least three books you need to get.  One thing: do exercises and code kata to improve your understanding of the language.  Of course, you need a good xUnit pattern.

Algorithms are particularity important and you should pick a book that details them -- again, in your language of choice. Design Patterns and Anti-Patterns are worth while knowing about in any languages whatsoever.

Bottom line: it takes time.  Do not rush.

ContentLicense: CC BY-SA 3.0


问:
What factors should be evaluated when determining a desktop software price?
What factors should be evaluated when determining a desktop software price?</p>

答:
People will pay whatever they think is a reasonable price.  </p>

<p>You need to do a survey of similar products, customer needs for said software, and have a good sale team.  I have seen software being sold for several tens of thousands per item and it be cheap.  I have seen software being sold for $1 and it being an utter waste of money. </p>

Body:
People will pay whatever they think is a reasonable price.

You need to do a survey of similar products, customer needs for said software, and have a good sale team.  I have seen software being sold for several tens of thousands per item and it be cheap.  I have seen software being sold for $1 and it being an utter waste of money.


答:
There are a few books that will help you a lot.
I suggest to have always next to you Code Complete. It is an invaluable reference. In a previous company where I worked this was also the book we gave every junior programmers after being hired.

The Pragmatic Programmer is also a really useful resource and it is pretty short, but I suggest you read it after Code Complete.

These books will get you started, then code, code, code and code more...but know when to stop, your software will never be perfect.


问:
Solutions to C# 5 async re-entrancy
So, something's been bugging me about the new async support in C# 5:

The user presses a button which starts an async operation. The call returns immediately and the message pump starts running again - that's the whole point.

So the user can press the button again - causing re-entrancy. What if this is a problem?

In the demos I've seen, they disable the button before the await call and enable it again afterwards. This seems to me like a very fragile solution in a real-world app.

Should we code some sort of state machine that specifies which controls must be disabled for a given set of running operations? Or is there a better way?

I'm tempted to just show a modal dialog for the duration of the operation, but this feels a bit like using a sledgehammer.

Anyone got any bright ideas, please?

EDIT:

I think disabling the controls that shouldn't be used while an operation is running is fragile because I think it will quickly become complex when you have a window with many controls on it. I like to keep things simple because it reduces the chance of bugs, both during the initial coding and the subsequent maintenance.

What if there is a collection of controls that should be disabled for a particular operation? And what if multiple operations are running concurrently?

答:
So, something's been bugging me about the new async support in C# 5: The user presses a button which starts an async operation. The call returns immediately and the message pump starts running again - that's the whole point. So the user can press the button again - causing re-entrancy. What if this is a problem?

Let's start by noting that this is already a problem, even without async support in the language. Lots of things can cause messages to be dequeued while you're handling an event.
You already have to code defensively for this situation; the new language feature just makes that more obvious, which is goodness.

The most common source of a message loop running during an event causing unwanted re-entrancy is DoEvents. The nice thing about await as opposed to DoEvents is that await makes it more likely that new tasks are not going to "starve" currently-running tasks. DoEvents pumps the message loop and then synchronously invokes the re-entrant event handler, whereas await typically enqueues the new task so that it will run at some point in the future.

In the demos I've seen, they disable the button before the await call and enable it again afterwards. I think disabling the controls that shouldn't be used while an operation is running is fragile because I think it will quickly become complex when you have a window with many controls on it. What if there is a collection of controls that should be disabled for a particular operation? And what if multiple operations are running concurrently?

You can manage that complexity the same way you'd manage any other complexity in an OO language: you abstract the mechanisms away into a class, and make the class responsible for correctly implementing a policy. (Try to keep the mechanisms logically distinct from the policy; it should be possible to change up the policy without tinkering overmuch with the mechanisms.)

If you have a form with lots of controls on it which interact in interesting ways then you are living in a world of complexity of your own making. You've got to write code to manage that complexity; if you don't like that then simplify the form so that it isn't so complex.

I'm tempted to just show a modal dialog for the duration of the operation, but this feels a bit like using a sledgehammer.

Users will hate that.

Title: Solutions to C# 5 async re-entrancy


问:
Whether to put the business logic in Stored Procedure or Not?
There is always a debate over the topic - "Whether to put the business logic in Stored Procedure or Not?". If we decide not to use the ORM Tool and not to put the Business Logic in Stored Procedure then where would we put the Business Logic?

In my previous applications I have always preferred putting all of the Business Logic in Stored Procedures only. Then from .NET code I call these Stored Procedures using Data Access Application Blocks. SQLHelper etc. But this can not be the scenario all the time. So I did some googling but ended up in confusion.......

Any suggestionss...?

答: In my limited experience, I prefer to maintain data integrity with stored procedures and other database features.  For example, if I were implementing a transfer of funds between two accounts, I would write a stored procedure.  I find it valuable to be able to use multiple application languages.</p>

OwnerDisplayName: Pravin Patil


答:
While there are lots and lots of good resources on how to do and don't do things, in the end most important thing is seeing a lot of code and working with it and see how easy or complicated it is to maintain for yourself.

A good way to learn is to have somebody experienced to do the initial design and than review your code and show you useful techniques as you have use for them. So if you by any chance manage to persuade your bosses to hire at least one software engineer with experience in leading (small) software projects and designing software to lead the projects, I think it would be the best option.

If you can't get anybody to couch you, there is these days strong open-source movement. Perhaps you use some open source tools in your work, so try to fix bugs in them or add simple features that you have use for and discuss how to do those things with respective community. It is a unseful hands-on learning exercise to learn how to apply any general rules you'll find in the books on actual practical problems.


问:
Are there any real-world cases for C++ without exceptions?
In When to use C over C++, and C++ over C? there is a statement wrt. to code size / C++ exceptions:

Jerry answers (among other points):

(...) it tends to be more difficult to produce truly tiny executables with C++. For really small systems, you're rarely writing a lot of code anyway, and the extra (...)

to which I asked why that would be, to which Jerry responded:

the main thing is that C++ includes exception handling, which (at least usually) adds some minimum to the executable size. Most compilers will let you disable exception handling, but when you do the result isn't quite C++ anymore. (...)

which I do not really doubt on a technical real world level.

Therefore I'm interested (purely out of curiosity) to hear from real world examples where a project chose C++ as a language and then chose to disable exceptions. (Not just merely "not use" exceptions in user code, but disable them in the compiler, so that you can't throw or catch exceptions.) Why does a project chose to do so (still using C++ and not C, but no exceptions) - what are/were the (technical) reasons?

Addendum: For those wishing to elaborate on their answers, it would be nice to detail how the implications of no-exceptions are handled:

STL collections (vector, ...) do not work properly (allocation failure cannot be reported)

new can't throw

Constructors cannot fail

答:
Almost any console game out there is in C++ with exception deactivated, even today. In fac it's the default setup for C++ compilers targeting those consoles. Sometimes some C++ features are not guaranteed to work correctly on those compilers, like multiple inheritance (I'm thinking about a very well known console default compiler for example).

Also, another example is Arduino hardware SDK usnig gcc without exception activated in C++, and other things like no STL provided.

There are some technical reasons, good or bad, whatever, it's not my advice but reasons I've heard :

Most consoles are really embedded systems with limited memory and processing time. Maybe it will not be so true in future consoles, but current ones are still prety restrictive compared to a PC. Some portable consoles are erally harder to program than any smartphone, for example the NDS. Exception feature does add memory and a little bit of speed cost, even if you don't use it. You can check yourself, it's true even on PC.

Video games on console can't crash. They have to be tested in a way that avoid any crash or any dead-end, any showstoper. That's why console manufacturers asks the games to be heavily checked before publication. That also mean that exception management add cost that isn't really useful in case of console game. It's better in smartphone for example because there might be some ways to recovery or the add some code to email you the problem. Closed platforms like most consoles don't allow this. So an exception system isn't really necessary after all. You "just have to make it work correctly". ;)

Exception management, when you don't allow errors and crashes, means you have to implement an error management strategy. Such system might be complex enough to make someone work a lot of time to make it useful. Game developers don't have luxury to work on features that are thought to be useful in crashes...

The compiler don't allow it (yet). Yes, it happen.

I think exceptions can be useful even in games but that's truee that on console games it's not really useful.

Update:

I'm adding another surprising example here: LLVM/CLang dont use exception nor RTTI for the followin reasons:

In an effort to reduce code and executable size, LLVM does not use
  RTTI (e.g. dynamic_cast<>) or exceptions. These two language features
  violate the general C++ principle of "you only pay for what you use",
  causing executable bloat even if exceptions are never used in the code
  base, or if RTTI is never used for a class. Because of this, we turn
  them off globally in the code.

That said, LLVM does make extensive use of a hand-rolled form of RTTI
  that use templates like isa<>, cast<>, and dyn_cast<>. This form of
  RTTI is opt-in and can be added to any class. It is also substantially
  more efficient than dynamic_cast<>.

CLang is well known for its speed ofr compilation and explicit errors, but also its one rare compiler that have really easy-to-follow code.


问:
"sell" coding my next project in an unfamiliar language
I want to code my next work project in a language I'm unfamiliar with (python). I can think of plenty of reasons from my point of view why its a good idea (not least of all because it sounds fun). However my manager will probably ask me why. I'm a little stumped on the advantages from his point of view.

EDIT: I normally code in C#

EDIT2 My reasons for wanting to code in another language;

It will make an easy project much harder so I will learn more and it will be more interesting

I have just read a book on python. I want the chance to apply it in a business application so I properly understand it

It will increase my skill set and make me more employable

Python looks fun

答: Shouldn't you approach it from the point of "what should I do that is best for the company" rather than "what do I want to do and how can I convince them of its value."?</p>


答:
I would rather choose a language that is better for the task I have to accomplish. Which kind of project? This would not only be of benefit for your company but also for you (choosing the wrong tool can cause trouble later).

If Python is something that could enter in your company/group strategy and you want to learn it, I would be honest with your manager and tell it that you want to do it in Python to learn Python. He will be then able to choose if the cost/benefit ratio is OK.

BTW what is the alternative? (i.e., the 'default' language)?

Title: "sell" coding my next project in an unfamiliar language

Body:
I want to code my next work project in a language I'm unfamiliar with (python). I can think of plenty of reasons from my point of view why its a good idea (not least of all because it sounds fun). However my manager will probably ask me why. I'm a little stumped on the advantages from his point of view.

EDIT: I normally code in C#

EDIT2 My reasons for wanting to code in another language;

It will make an easy project much harder so I will learn more and it will be more interesting

I have just read a book on python. I want the chance to apply it in a business application so I properly understand it

It will increase my skill set and make me more employable

Python looks fun


答:
Some advantages (depending on what kind of project you want to accomplish and what the alternative language would be ;)

clean OOP with dynamic typing (so inherently generic)

good for rapid prototyping

Mixable with other languages

open source and popular

portable

Powerful language constructs and toolkits / libraries

good for internet scripting

automatic memory management

Fun and fast to learn and use

Other then that, think about why you want to learn Python, and you'll probably find several benefits for your company, too. If not, Python is not suitable, and you shouldn't pick it.


问:
Why are there so many competing filesystem designs?
Just a quick question, but why are there so many file systems still competing and in use today? (ntfs, fat32, ext3(ffs), etc)

It seems that file system designers could agree upon the best aspects of each type of system and implement a "best" filesystem, no? Just a thought, since these filesystems have been around for a while now, and it should be at least somewhat apparent which ones have good qualities over others, and we could just combine the good in each and create an ultimate system that is much better

答:
Here's another concrete example of why you would need a separate file system or extend the functionality of an existing FS.

Say you are a database vendor and would like to reduce the complexity of managing striping / mirroring of data to improve IO. You will feel the need to extend the functionality of basic file systems as Oracle did with ASM (Automated Storage Manager) which is like a Logical Volume Manager.


问:
What should we do to make Morning Standup meetting better and effective
Here in my office, we made it a practice to come before 9 AM (in any condition as decided by management) and start with a Standup Meeting. Here we start with discussing with issues of previous day, any updates from manager (by leads) and the work plan for today.

This meeting may sound good and process oriented , but some times if there is a show down then it ruins the morning mood or if there is a difference in opinion then again it is not a good thing to start with.

So, HR and Management decides that initially we will discuss personal matters  for 10 to 15mins and then we will jump to technical and official discussion.For 15 minutes everyday, are you serious , I don't get a topic to discuss for 15mins every day with my lead who is much older than me and never discussed anything in personal till now and you want to start with it just like that!!! So it is back to square one. Every one (Amazingly in all the teams) is discussing again technical aspects only in the morning /stand up meeting.

So here it comes, today I have a lunch with management and the topic for discussion is:

How to make Nice Day(Morning/Standup) meetings effective?

答:
I've found it easier to talk about things on the task board/card wall/kanban board .
Talk only about what is blocking the movement of cards on the wall. Take anything else off line, if it it is not related to the cards on the wall.

This keeps the standup focussed and relevant.
Only let people in the team talk ( those who are working on things that are on the wall) everyone else has to be silent till the stand up is over

Avoid technical discussions. Standups are about progress , removing blockers and communicating what everyone else is doing.

Only let one person talk at a time. Have a standup token, only the person having the token may talk and they may hold the token only for a minute.

Be disciplined and brutal. For a team of 5-6 shouldn't last longer than 10 minutes. Make it quick and snappy and full of energy.

The stand up is for the team, no one else, not HR, not Management and not even the CEO. The team decides when to have the standup and the team sets the agenda.

Have a look at common standup smells
http://martinfowler.com/articles/itsNotJustStandingUp.html

ContentLicense: CC BY-SA 2.5


答: Yet another example of why there can never be a perfect file system for everyone: HDDs and SSDs have very different read/write access characteristics.  An SSD-optimized filesystem would probably work best by fragmenting files like crazy but with every fragment the page size of the SSD itself; this would perform terribly on an HDD.  An HDD-optimized filesystem tries to keep files as unfragmented as possible and even puts frequently-used files in the "hot" area on the faster-spinning outer portion of the platter; these characteristics wouldn't help SSD read speeds at all, and puts a huge encumbrance on how they are written to.</p>

Title: Why are there so many competing filesystem designs?

Body:
Just a quick question, but why are there so many file systems still competing and in use today? (ntfs, fat32, ext3(ffs), etc)

It seems that file system designers could agree upon the best aspects of each type of system and implement a "best" filesystem, no? Just a thought, since these filesystems have been around for a while now, and it should be at least somewhat apparent which ones have good qualities over others, and we could just combine the good in each and create an ultimate system that is much better


问:
What is the accepted style for using the `this` keyword in Java?
I come from languages like Python or Javascript (and others that are less object-oriented) and I am trying to improve my working knowledge of Java, which I know only in a superficial way.

Is it considered a bad practice to always prepend this to the current instance attributes? It feels more natural to me to write

```<code>...
private String foo;

public void printFoo() {
    System.out.println(this.foo);
}
...
</code>```

than

```<code>...
private String foo;

public void printFoo() {
    System.out.println(foo);
}
...
</code>```

as it helps me to distinguish instance attributes from local variables.

Of course in a language like Javascript it makes more sense to always use this, since one can have more function nesting, hence local variables coming from larger scopes. In Java, as far as I understand, no nesting like this is possible (except for inner classes), so probably it is not a big issue.

In any case, I would prefer to use this. Would it feel weird and not idiomatic?

答:
One place I consistently use 'this' is setters and or constructors:

```<code>public void setFoo(String foo) {
    this.foo = foo;
}
</code>```

Other than that, I don't feel it is necessary to add it.
When reading the body of a method, parameters and locals are right there - and fairly easy to keep track of (even without the IDE help). Also locals and fields tend to be of different nature (object state vs transient storage or parameter).

If there is any confusion about what's a variable and what's a field, it probably means a method has too many variables/parameters, is too long and too complex, and should be simplified.

If you choose to use 'this' to tag fields, I would recommend to make sure the convention is always strictly followed - it would be really easy to start assuming no 'this' means it's a local and break stuff based on the assumption.

edit: I also end up using this in equals, clone or anything which has a 'that' parameter of the same object type:

```<code>public boolean isSame(MyClass that) {
    return this.uuid().equals(that.uuid());
}
</code>```

Body:
One place I consistently use 'this' is setters and or constructors:

public void setFoo(String foo) {
    this.foo = foo;
}

Other than that, I don't feel it is necessary to add it.
When reading the body of a method, parameters and locals are right there - and fairly easy to keep track of (even without the IDE help). Also locals and fields tend to be of different nature (object state vs transient storage or parameter).

If there is any confusion about what's a variable and what's a field, it probably means a method has too many variables/parameters, is too long and too complex, and should be simplified.

If you choose to use 'this' to tag fields, I would recommend to make sure the convention is always strictly followed - it would be really easy to start assuming no 'this' means it's a local and break stuff based on the assumption.

edit: I also end up using this in equals, clone or anything which has a 'that' parameter of the same object type:

public boolean isSame(MyClass that) {
    return this.uuid().equals(that.uuid());
}


答:
There are good answers here.

A big spin in your favor is the simple fact that you want to know.

Much of software engineering (which you should take with healthy skepticism, of course) is about how to do it in ways you won't regret later.
One example is the use of a source code version control system.
Another is dividing the code into files so it's easier to work on it piecemeal.
Another is to be a stickler about orderliness - code formatting and naming conventions.
The exact conventions don't matter as much as being consistent about it.

That way, when you come back to the code in a year or more, you won't think "Who made this mess?"
You will be able to find things and change them without too much risk of breakage.**

A good way to get started is to find various example programs and work through them.
Then you can adapt them to your needs.

** One of my biggest headaches is trying to work with code written by people who did not think formatting or naming mattered.


问:
Architecture: for a Single website to be supported for different Clients
I have developed a system with one company profile.
The system is built using WCF services, asp.net.

Now another company wants to use our system as well. And they might need some customization and some of their data elements are different. So I am planning to create a separate database for the new company and branch the business logic layer.

I thought of different options to architect this and ended up with the following. So what is the best way to design a system of this sort.

Approach A:
Expose the methods as two different WCF services one for each company. So there will be one WCF client interface (IClient) but two different Service classes for each company implenting them. ClientAService : IClient, ClientBService : IClient.

Problem:
The problem with this  is all my datacontracts and datamembers are exposed to the client in 2 different namespaces. (ClientAService.ObjectABC and ClientBService.ObjectABC). So all the objects that I use in the website are conflicted. ie(when I have a list of ObjectABC in a datasource in the webpages, the website don't understand whether its from ClientAService or ClientBService.

Approach B:
Expose the methods as a single WCF Client, but 2 different business logic layer. But they will use the same datacontracts. So the methods will return the same datatype.

so I will have one service class

```<code>ClientService : IClient

{
public <ObjectABC> Method1(String Companycode)
{
if(CompanyCode == "A")
    return new AbusinessLogic().Method1();
else if(CompanyCode == "B")
    return new BbusinessLogic().Method1();
}
}
</code>```

Problem:
The only problem I can think of right now for every new company, I have add the above else if part for all my methods.

I am also open to know if this can done in any other better way than the stated options.

note: I was told that there might be more companies to be added in future.

答:
I am in a similar problem at the moment and I am sure it is a common one.  I inherited an application that was rapidly developed for a single client, however it was well known before development even started that it would need to be highly customizable for multiple clients that may exist in the future.

Typical YAGNI principles applied and it was infuriatingly tailored to specific customer requirements and NOT to higher level company requirements.  Basically this was a misinterpretation of the ACTUAL client.  The actual client was the company itself, the development team should have developed software that met the companies requirements for a configurable and customizable product.  The customer is just the client for the company at that point.

The best answer here isn't one that can be solved at the low level design like you are thinking.  This is a high level design and architecture issue.  The best approach is to revist your high level design and identify global components and global business logic that will be the same or mostly similar amongst all clients.  If you have trouble even finding basic similarities then STOP because your new customer requirements are probably so wildly different that it warrants a seperate application.

Once isolating common business logic and components, identify individual and specific customer needs that are unique.  Unique requirements specific to your current customer can be componentized out, while unique requirements for your new customer can be planned with requirements and user stories.

Additional development tasks would be to find specific static content and resources and make those configurable and dynamic (Eg. static helper text/tooltips specific to current customer, email and other message alerts, specific images and logos, etc...).  These can be packaged into resource bundles typically that are unique to a specific customer deployment.

Other examples of custom components would be different aspect oriented features for different customers, (Eg. Customer 1 needs Login form authentication provider, Customer 2 needs LDAP Integrated Single Sign On authentication provider, etc...)  Selecting a good framework and architecture that supports configrable aspect oriented features is a good step.  Dependency Injection/Inversion of Control frameworks are a good approach as well.

With a bit of refactoring and a solid well planned redesign, an existing application tailored to a specific customer can be turned into a customizable solution that meets the needs of many different types of customers.


答:
Perhaps in this regard, it's worth mentioning Embedded C++. Embedded C++ is a variant of C++ designed (obviously enough) for embedded systems. It's basically a proper subset of C++, with (among other things) templates, namespaces, and exception handling removed.

I should add that while EC++ made a bit of a splash when it was new, they seem to have mostly gone fairly quiet. I'm not sure if people have lost interest, or their first attempt was simply so perfect that nobody's seen any reason to mess with it for a decade or so. <closed captioning for the humor impaired>Yeah, right!</closed captioning>

Title: Are there any real-world cases for C++ without exceptions?

Body:
In When to use C over C++, and C++ over C? there is a statement wrt. to code size / C++ exceptions:

Jerry answers (among other points):

(...) it tends to be more difficult to produce truly tiny executables with C++. For really small systems, you're rarely writing a lot of code anyway, and the extra (...)

to which I asked why that would be, to which Jerry responded:

the main thing is that C++ includes exception handling, which (at least usually) adds some minimum to the executable size. Most compilers will let you disable exception handling, but when you do the result isn't quite C++ anymore. (...)

which I do not really doubt on a technical real world level.

Therefore I'm interested (purely out of curiosity) to hear from real world examples where a project chose C++ as a language and then chose to disable exceptions. (Not just merely "not use" exceptions in user code, but disable them in the compiler, so that you can't throw or catch exceptions.) Why does a project chose to do so (still using C++ and not C, but no exceptions) - what are/were the (technical) reasons?

Addendum: For those wishing to elaborate on their answers, it would be nice to detail how the implications of no-exceptions are handled:

STL collections (vector, ...) do not work properly (allocation failure cannot be reported)

new can't throw

Constructors cannot fail


答: When you are trying to keep executable memory down. Typically done on embedded (or mobile) systems. For desktops apps its never needed however on servers it might be considered if you want as much ram as possible for the web server or for sql.</p>


答:
Is there any hint in your company that you will be leaving the Microsoft stack or a desire to get away from being totally locked-in? Having developers with knowledge in other areas would make this easier.

There are suggestions to only use a particular language if there is a specific benefit to the project. This always seems difficult to do when you haven't learned a language. How do you know what you don't know? Sure you can research or ask on SO and either get your question closed or at best, receive a 'it depends' reply.

It may help you develop new techniques to handling current problems.

There may be an advantage to being a dual-language shop when it comes to recruiting talent. Your next programmer may have a Python preference, but is willing to do some C# work as well.

So many places complain that their developers are set in their ways and don't want to learn new things. Start a small project and show you're eager to learn, but willing to work within the parameters of what helps your company.


问:
Is it worth registering software with the U.S. Copyright Office?
nolo.com says: "If you want to stop someone from using or otherwise infringing on your work, you must sue the infringer in federal court. However, in order to do so, you must first have registered the copyright with the U.S. Copyright Office."

Is it true that the only way to take legal action against software copyright infringers in the U.S. is to first register with the U.S. Copyright Office? And is it true that that's the only way to recover statutory damages?

Are there other benefits of registering software with the U.S. Copyright Office?

What are the costs, besides the fee and the hassle of re-registering new versions of the software?

答:
A work does not have to be registered with the U.S. Copyright Office to be considered a copyrighted work.

Copyright protection subsists from the time the work is created in
  fixed form. The copyright in the work of authorship  immediately
  becomes the property of the author who created the work.  No publication or registration or other action
  in the Copyright Office is required to secure copyright.

http://www.copyright.gov/circs/circ1.pdf

However, you do have to be registered with the U.S. Copyright Office to sue for statutory damages against someone violating your copyright.

The benefits of copyright registration are outlined on page 7 of the circular I linked.  Among these advantages are the following:

Registration establishes a public record of the copyright  claim.

Registration allows you to file an infringement suit in court, for works of U.S. origin.

If made before or within five years of publication, registration will establish prima facie evidence in court of  the validity of the
  copyright.

If registration is made within three months after publication of the work or prior to an infringement of the work,
  statutory damages and attorney’s fees will be available to  the copyright owner in court actions. Otherwise, only an  award of actual
  damages and profits is available to the  copyright owner.

Registration allows the owner of the copyright to record  the registration with the U.S. Customs Service for protection against the
  importation of infringing copies.


答:
Is it true that the only way to take legal action against software copyright infringers in the U.S. is to first register with the U.S. Copyright Office? And is it true that that's the only way to recover statutory damages?

In the United States, copyright is attached as soon as the work is created. Registration is not necessary unless you wish to seek statutory damages against an infringer 1. You can seek litigation and actual damages without registration. However, registration does provide a legal record that can assist with matters of litigation of all kinds.

Are there other benefits of registering software with the U.S. Copyright Office?  What are the costs, besides the fee and the hassle of re-registering new versions of the software?

I would recommend consulting a lawyer who specializes in intellectual property or software law. There are a lot of reasons why you might want to consider registrating versus not registering, and a lawyer with this expertise would be best suited to help you determine the best course of action to help you legally protect your work.

1: There appears to be some confusion on this point. Most sources that I've found say that the Berne Convention allows you to seek actual damages from an infringer without copyright registration. However, [Robert Harvey links to a document from the US Copyright Office] that says registration allows you to file infringement suits, possibly indicating that registration is required to file any kind of legal action in the United States (a signer of the Berne Convention). Best course of action: Consult a lawyer, specifically an intellectual property or software law specialist.

Title: Is it worth registering software with the U.S. Copyright Office?

Body:
nolo.com says: "If you want to stop someone from using or otherwise infringing on your work, you must sue the infringer in federal court. However, in order to do so, you must first have registered the copyright with the U.S. Copyright Office."

Is it true that the only way to take legal action against software copyright infringers in the U.S. is to first register with the U.S. Copyright Office? And is it true that that's the only way to recover statutory damages?

Are there other benefits of registering software with the U.S. Copyright Office?

What are the costs, besides the fee and the hassle of re-registering new versions of the software?


答:
In your list you mention an old filesystem used because a better one is no available however it is fast.

There are other filesystems. I heard google filesystem is mostly for fast duplication/redundancy if one harddrive or server goes down. I remember hearing of another filesystem made for many small files and to be used on a system for lots of request on small file (thumbnails).

Essentially they have difference goals and or may be propriety vs open source.


答:
You suck in coding. Yes.

But - this doesn't mean you can't deliver software, that makes people happy ;)

Be humble. Write the "business" logic, that you need. Use library code for everything else. Do not attempt to write fundamental algorithms (like array sorting), do not use any "fancy tricks", stick to some draconian code-convention.

Use good IDE. This is essential, as it will help you to format your code and track typos / simple mistakes.

Read books like "Code Complete" and "Pragmatic Programmer", try to force yourself and learn OOP (its simple, and will help you keep your code more maintainable).

Use SVN, commit often, - so you will be able to revert your changes (when you will ruin something).

Find somebody, who is a real programmer, with academic background, if possible. So you will be able to talk with him sharing your newbie problems, and getting enlightening answers.

And, of course, the most important thing is to also keep coding, coding, coding.

p.s.: if you are able to write C++ code that works, and you write neural networks(!) - then your brain is well suited for programming ;) Good luck!


答:
After you have finished reading the article by Joel Spolsky take a look at this Software pricing demystified

Edit

To quickly summarize the info from the article, pricing a product is hard to do in the first attempt (especially if this is your first product). The best thing to do is to start with a good guess and then optimize.

You need to think about your product and determine:

what's the objective value of your product

what's the perceived value of your product

who are your customers / the size of the market

Objective value of your product is easy to determine: SavingsByUsingYourApp - AppPrice = Objective value. The perceived value is a little it more complicated:

Perceived value can be different than objective value, and it can
  affect sales in ways that the demand curve does not predict.  For
  example, when buying a brand-name product, you are intentionally
  paying a premium because the perceived value is higher, even if the
  objective value is the same. Some brands purposely price higher in
  order to increase the perceived value and thus sell more.

You obviously need to determine who are your customers. Also, research the market and your competition. Sales and marketing strategies for selling an app to a big company are almost certainly different than selling e.g. a mobile app for kids.

Body: What factors should be evaluated when determining a desktop software price?</p>


问:
DDD - Does an aggregate root's repository handle saving aggregates?
I am using a DDD-like approach for a greenfield module of an existing application; it's not 100% DDD due to architecture but I'm trying to use some DDD concepts.  I have a bounded context (I think that's the proper term - I'm still learning about DDD) consisting of two Entities: Conversation and Message.  Conversation is the root, as a Message doesn't exist without the conversation, and all messages in the system are part of a conversation.

I have a ConversationRepository class (although it's really more like a Gateway, I use the term "Repository") which finds Conversations in the database; when it finds a Conversation it also creates (via Factories) a list of messages for that Conversation (exposed as a property).  This seems to be the correct way of handling things as there doesn't seem to be a need for a full-blown MessageRepository class as it only exists when a Conversation is retrieved.

However, when it comes to saving a Message, is this the responsibility of the ConversationRepository, since it's the aggregate root of Message?  What I mean is, should I have a method on ConversationRepository called, say, AddMessage that takes a Message as it's parameter and saves it to the database?  Or should I have a separate repository for finding/saving Messages?  The logical thing seems to be one repository per Entity, but I've also heard "One repository per Context".

答:
The blue book is definitely worth a read if you want to get the best out of the DDD approach. DDD patterns are not trivial and learning the essence of each of them will help you ponder when to use which pattern, how to divide your application in layers, how to define your Aggregates, and so on.

The group of 2 entities you're mentioning isn't a Bounded Context - it's probably an Aggregate. Each Aggregate has an Aggregate Root, an Entity that serves as a single entry point to the Aggregate for all other objects. So no direct relation between an Entity and another Entity in another Aggregate that is not the Aggregate Root.

Repositories are needed to get hold of Entities that are not easily obtained by traversal of other objects. Repositories usually contain Aggregate Roots, but there can be Repositories of regular Entities as well.

In your example, Conversation seems to be the Aggregate Root. Maybe Conversations are the starting point of your application, or maybe you want to query them with detailed criteria so they are not satisfyingly accessible through simple traversal of other objects. In such a case you can create a Repository for them that will give the client code the illusion of a set of in-memory Conversations to query from, add to or delete from directly.
Messages on the other hand are easily obtained by traversal of a Conversation, and you might not want to get them according to detailed criteria, just all of a Conversation's Messages at once, so they might not need a Repository.

ConversationRepository will play a role in persisting Messages, but not such a direct role as you mention. So, no AddMessage() on ConversationRepository (that method rather belongs in Conversation itself) but instead, each time the Repository will persist a Conversation, it's a good idea to persist its Messages at the same time, either transparently if you use an ORM framework such as (N)Hibernate, using ad hoc SQL if you choose so, etc.


答:
Jerry said: ...the result isn't quite C++ anymore, while my metaphor is that it is clearly C++, just a slightly different dialect because programs utilize other forms, conventions, and written styles.

Here are my primary reasons for disabling them:

Binary Compatibility

Crossing language and translation boundaries is not universally well defined, or undefined. If you want to guarantee your program operates within the domain of defined behavior, you will need to quarantine exceptions at module exit points.

Executable Size

Here are the binary sizes of an exception free program I wrote, built without and with exceptions enabled:

Without exceptions:

executable + dependencies: 330

final stripped executable (release build): 37

With exceptions:

executable + dependencies: 380

final stripped executable (release build): 44

Reminder: That's a collection of libraries and programs which contain zero throws/catches. The compiler flag does enable exceptions in the C++ standard library. Therefore, the cost in the real world is more than 19% seen in this example.

Compiler: apple gcc4.2 + llvm. Sizes in MB.

Speed

Despite the term "zero cost exceptions", they still add some overhead even when nothing ever throws. In the above case, it is a performance critical program (Signal Processing, Generation, Presentation, Conversions, with large data sets/signals etc.). Exceptions are not a necessary feature in this design, while performance is very important.

Program Correctness

Seems like a strange reason... If throwing is not an option, you must write relatively strict, correct, well tested programs to guarantee your program executes correctly, and that clients use the interfaces correctly (if you give me a bad argument or do not check an error code, then you deserve UB). The result? Implementation quality improves greatly and problems get fixed quickly.

Simplicity

Exception handling implementations aren't often kept up to date. They also add a lot of complexity because an implementation can have many many many exit sequences. It's simpler to read and maintain highly complex programs when they use a small set of well defined, typed, exit strategies which bubble up to and are handled by the client. In other cases, the implementations may over time implement more throws or their dependencies may introduce them. Clients cannot easily or appropriately defend against all these exits. I write and update a lot of libraries, there is frequent evolution and improvement. Attempting to keep that all in synch with exception exit sequences (in a large codebase) would not be a good use of time, and would likely add a lot of noise and cruft. Due to increased program correctness and more tests, many (certainly not all) of the potential issues/exits can be ruled out.

History/Existing Code

In some cases, they were never introduced for historical reasons. An existing codebase did not use them, changing the programs could take man-years and make it really ugly to maintain because of overlap in conventions and implementations.

Downsides

Of course, there are downsides, the biggest are: Incompatability (incl. binary) with other libraries, and the fact that you will have to implement a good amount of programs to fit this model.


答:
Google doesn't approve of exceptions in their C++ Style Guide, mostly for historical reasons:

On their face, the benefits of using exceptions outweigh the costs,
  especially in new projects. However, for existing code, the
  introduction of exceptions has implications on all dependent code. If
  exceptions can be propagated beyond a new project, it also becomes
  problematic to integrate the new project into existing exception-free
  code. Because most existing C++ code at Google is not prepared to deal
  with exceptions, it is comparatively difficult to adopt new code that
  generates exceptions.

Given that Google's existing code is not exception-tolerant, the costs
  of using exceptions are somewhat greater than the costs in a new
  project. The conversion process would be slow and error-prone. We
  don't believe that the available alternatives to exceptions, such as
  error codes and assertions, introduce a significant burden.

Our advice against using exceptions is not predicated on philosophical
  or moral grounds, but practical ones. Because we'd like to use our
  open-source projects at Google and it's difficult to do so if those
  projects use exceptions, we need to advise against exceptions in
  Google open-source projects as well. Things would probably be
  different if we had to do it all over again from scratch.

There is an exception to this rule (no pun intended) for Windows code.

(Editor's emphasis)


问:
Do we need test data or can we rely on unit tests and manual testing?
We're currently working on a medium/large PHP/MySQL project. We're doing unit testing with PHPUnit & QUnit and we have two full time testers that are manually testing the application. Our test (mock) data is currently created with SQL scripts.

We have problem with maintaining scripts for test data. The business logic is pretty complex and one "simple" change in the test data often produces several bugs in the application (which are not real bugs, just the product of invalid data). This has become big burden to the whole team because we are constantly creating and changing tables.

I don't really see the point of maintaining the test data in the scripts because everything can be manually added in the application in about 5 minutes with the UI. Our PM disagrees and says that having project that we can’t deploy with test data is a bad practice.

Should we abandon maintenance of the scripts with test data and just let the testers to test the application without data? What’s the best practice?

答:
This is a very common problem and very difficult one as well. Automated tests that run against a databse (even an in-memory database, such as HSQLDB) are usually slow, non-deterministic and, since a test failure only indicates that there is a problem somewhere in your code or in you data, they are not much informative.

In my experience, the best strategy is to focus on unit tests for business logic. Try to cover as much as possible of your core domain code. If you get this part right, which is itself quite a challenge, you will be achieving the best cost-benefit relationship for automated tests. As for the persistence layer, I normally invest much less effort on automated tests and leave it to dedicated manual testers.

But if you really want (or need) to automate persistence tests, I would recommend you to read Growing Object-Oriented Software, Guided by Tests. This book has a whole chapter dedicated to persistence tests.


答:
I /never/ use exceptions. There are a number of reasons for this, but the two main reasons are that I have never needed them to produce robust code and that they reduce the performance at runtime.

I have worked on production code that is both using and disabling exceptions - the code that allowed exceptions was uniformly worse. In some places exceptions were used for genuine flow control rather than error handling, which is very heavyweight, anti-performance and difficult to debug. In general debugging problems in the exception filled code was more difficult than in the exception-free code - partly down to the stack and intrinsic difficulties of the exception mechanism, but much more than that it was because of the lazy code that was encouraged as a result of having exception handling available.

There is nothing seriously wrong with exceptions themselves /if you don't care about performance/ and don't have time to do something properly - they are a language feature for error handling and a good substitute for a proper error handling mechanism. However, there are almost always /better/ ways to handle errors - like with your own logic (its hard to elaborate on this - it is almost common sense). If its not your error, but comes from a library (e.g. the standard library) then you have to respect the choice of exceptions or have some crash, but I'd always question that choice. I have never seen a situation where exceptions were actually the best solution.

Assertions are more debuggable, error codes are less heavyweight... between the two, if used properly, you get easier to read, debug and maintain code which is faster. Its wins all round...


答:
Do you need to protect your software?

Its a dangerous area - in particular people have already copyrighted and patented all kinds of things that take 5-10 minutes of trying to solve the problem to independently invent.

You might have infringed many copyrights and patents already...

My opinion on this is to ignore the madness and continue with common sense in the hopes that if anyone does try and bring litigation I can make a persuasive enough argument to have it laughed out of court. Its not a particularly safe stance to take though. Although I believe there is ample precedent for US copyright and patents having no merit outside of the US...


答:
You should probably not take risks with your employer's time/money for your own benefit... just a thought.

Learn Python on your own time - then making an argument for using it will happen naturally if its appropriate.


问:
Why in the world does a heap need to make sure it allocates in 8-byte alignments?
4-bytes = word;
8-bytes = 2x word

Then why doesn't the heap just go with 4-byte alignment (because it will be grabbing a word at a time anyway, right?)

If we went with 8-byte alignments, why not 12? 16?

答:
Efficiency and CPU architecture. I remember when the Alpha chips came out, they could only read memory on 32 bit boundaries. If you wanted to read byte 3, you'd load a 32-bit number then have to rotate the result to isolate the byte you want. A traditional byte-by-byte string compare was quite inefficient in this architecture.

That being said, I'm not sure what modern processors do. It's been a while since I had to deal with this.


答: Symbian C++ (used on some Nokia mobile phones) doesn't use exceptions, at least not directly, because C++ compilers didn't reliably implement them when Symbian was first developed.</p>


答: Though Jan Hudec and Rachel have expressed related ideas, I would suggest using something like a Model-View architecture - express the state of the form in an object and tie the form elements to that state.  This would disable the button in a way that can scale for more complex scenarios.

Title: Solutions to C# 5 async re-entrancy

Body:
So, something's been bugging me about the new async support in C# 5:

The user presses a button which starts an async operation. The call returns immediately and the message pump starts running again - that's the whole point.

So the user can press the button again - causing re-entrancy. What if this is a problem?

In the demos I've seen, they disable the button before the await call and enable it again afterwards. This seems to me like a very fragile solution in a real-world app.

Should we code some sort of state machine that specifies which controls must be disabled for a given set of running operations? Or is there a better way?

I'm tempted to just show a modal dialog for the duration of the operation, but this feels a bit like using a sledgehammer.

Anyone got any bright ideas, please?

EDIT:

I think disabling the controls that shouldn't be used while an operation is running is fragile because I think it will quickly become complex when you have a window with many controls on it. I like to keep things simple because it reduces the chance of bugs, both during the initial coding and the subsequent maintenance.

What if there is a collection of controls that should be disabled for a particular operation? And what if multiple operations are running concurrently?


答:
I think you answered your own question with this:

It feels more natural to me to write

... this.foo ...

than

... foo ...

as it helps me to distinguish instance attributes from local variables.

If you are more comfortable using this. while improving your working knowledge with Java, then by all means use the thing (I think it's, in a way, the familiar Python self that you are relating to).

The thing is that, although people will give solid/pertinent arguments about using or not using this., it still sound like a debate, example given:

it makes the purpose of the variables clear vs. you should rewrite the code if it's not clear what each variable is;

this. is redundant if you spend your entire day in the IDE vs. I perform code reviews and make diffs on different versions using a comparator with no syntax highlighting;

not typing this. gains me important milliseconds of productivity vs. I get payed by key pressed and adding this. is like a pay raise :D;

etc etc

But bottom line is, that at the end of the day, it still resumes to personal preference and work environment.

Title: What is the accepted style for using the `this` keyword in Java?

Body:
I come from languages like Python or Javascript (and others that are less object-oriented) and I am trying to improve my working knowledge of Java, which I know only in a superficial way.

Is it considered a bad practice to always prepend this to the current instance attributes? It feels more natural to me to write

```<code>...
private String foo;

public void printFoo() {
    System.out.println(this.foo);
}
...
</code>```

than

```<code>...
private String foo;

public void printFoo() {
    System.out.println(foo);
}
...
</code>```

as it helps me to distinguish instance attributes from local variables.

Of course in a language like Javascript it makes more sense to always use this, since one can have more function nesting, hence local variables coming from larger scopes. In Java, as far as I understand, no nesting like this is possible (except for inner classes), so probably it is not a big issue.

In any case, I would prefer to use this. Would it feel weird and not idiomatic?


问:
Why is C not considered an 'object-oriented' language?
It seems that C has its own quasi-objects such as 'structs' that can be considered as objects (in the high-level way that we would normally think).

And also, C files themselves are basically separate "modules", right? Then aren't modules kind of like 'objects' too? I'm confused as to why C, which seems so similar to C++, is considered a low-level "procedural" language where as C++ is high-level "object-oriented"

*edit: (clarification) why and where, is the line drawn, for what an 'object' is, and isn't?

答: "structs" are data only.  The usual quick and dirty test of "object orientation" is: "Is there a structure that allows code and data to be encapsulated as a single unit?".  C fails that, and is hence procedural.  C++ passes that test.</p>


答: You kind of said it yourself. While C has things that are kind of like objects, they are still not objects, and that is why C is not considered an OOP language.</p>

Title: Why is C not considered an 'object-oriented' language?

Body:
It seems that C has its own quasi-objects such as 'structs' that can be considered as objects (in the high-level way that we would normally think).

And also, C files themselves are basically separate "modules", right? Then aren't modules kind of like 'objects' too? I'm confused as to why C, which seems so similar to C++, is considered a low-level "procedural" language where as C++ is high-level "object-oriented"

*edit: (clarification) why and where, is the line drawn, for what an 'object' is, and isn't?


答:
Short answer is "It doesn't". The alignment is associated with the implementation details of the heap manager, nothing more. Your heap manager may have an alignment requirement for various reasons, such as efficiency, architecture, whim of the writer or what ever. If you have a reason to care, please share it with us.

BTW:

4-bytes = word 8-bytes = 2x word

This is an assumption, is incorrect, and has lead to many varied, sometimes expensive and always inexcusable software porting problems. The size of a word depends on the hardware architecture, OS, language and compiler being used.

Title: Why in the world does a heap need to make sure it allocates in 8-byte alignments?

Body:
4-bytes = word;
8-bytes = 2x word

Then why doesn't the heap just go with 4-byte alignment (because it will be grabbing a word at a time anyway, right?)

If we went with 8-byte alignments, why not 12? 16?


答:
You need to look at the other side of the coin: C++.

In OOP, we think of an abstract object (and design the program accordingly), for example a car that can stop, accelerate, turn left or right, etc. A struct with a bundle of functions simply does not fit the concept.

With "real" objects we need to hide the members for instance, or we can also have inheritance with a real "is a" relationship and many more.

AFTER READING THE COMMENTS BELOW:  Well it's right that  (almost) everything can be done with C (that is always true), but at first glance I thought that what separates c from c++ is the way you think when designing a program.

The only thing that really makes the difference is the imposing of policies by the compiler.  i.e pure virtual function, and such. but this answer will only relate to technical issues, but I think the the main difference (as mentioned) is the original way you think while you code, since C++ gives you a better built in syntax for doing such things, instead of doing OOP in a somewhat clumsy way in C.


答:
Based on the very highest level principals:

An object is an encapsulation of data and behaviour in an interlinked way such that they operate as a whole that can be instantiate multiple times and worked on as a black box if you know the external interface.

Structs contain data but no behaviour and therefore can not be considered objects.

Modules contain both behaviour and data but are not encapsulated in such a way that the two are related and certainly can't be instantiated multiple times.

And that's before you get onto inheritance and polymorphism...


答:
The key word is "oriented", not "object". Even C++ code that uses objects but uses them like structs is not object oriented.

C and C++ can both do OOP (aside from no access control in C), but the syntax for doing it in C is inconvenient (to say the least), while the syntax in C++ makes it very inviting.  C is oriented to procedural, while C++ is oriented to objects, despite nearly identical core capabilities in that regard.

Code that uses objects to implement designs that can only be done with objects (usually meaning taking advantage of polymorphism) is object oriented code. Code that uses objects as little more than bags of data, even using inheritance in an object oriented language, is really just procedural code that is more complicated than it needs to be. Code in C that uses function pointers that are changed around at runtime with structs full of data is kinda doing polymorphism, and could be said to be "object oriented", even in a procedurally oriented language.


答:
It seems that C has its own quasi-objects such as 'structs' that can be considered as objects

Let's together you and I read through the Wikipedia page on object oriented programming and check off the features of C-style structs that correspond to what is traditionally considered to be object-oriented style:

(OOP) is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions

Do C structs consist of fields and methods together with their interactions? No.

Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance.

Do C structs do any of these things in a "first class" way? No. The language works against you every step of the way.

the object-oriented approach encourages the programmer to place data where it is not directly accessible by the rest of the program

Do C structs do this? No.

An object-oriented program will usually contain different types of objects, each type corresponding to a particular kind of complex data to be managed or perhaps to a real-world object or concept

Do C structs do this? Yes.

Objects can be thought of as wrapping their data within a set of functions designed to ensure that the data are used appropriately

No.

each object is capable of receiving messages, processing data, and sending messages to other objects

Can a struct itself send and receive messages? No. Can it process data? No.

OOP data structures tend to "carry their own operators around with them"

Does this happen in C? No.

Dynamic dispatch ... Encapsulation ... Subtype polymorphism ... Object inheritance ...
  Open recursion ... Classes of objects ... Instances of classes ... Methods which act on the attached objects ... Message passing ... Abstraction

Are any of these features of C structs? No.

Precisely which characteristics of structs do you think are "object oriented"? Because I can't find any other than the fact that structs define types.

Now, of course you can make structs that have fields that are pointers to functions. You can make structs have fields that are pointers to arrays of function pointers, corresponding to virtual method tables. And so on. You can of course emulate C++ in C. But that is a very non-idiomatic way to program in C; you'd be better off just using C++.

And also, C files themselves are basically separate "modules", right? Then aren't modules kind of like 'objects' too?

Again, what characteristics of modules are you thinking of that makes them act like objects? Do modules support abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance?

Abstraction and encapsulation are pretty weak. Obviously modules are modular; that's why they're called modules. Messaging? Only in the sense that a method call is a message and modules can contain methods. Polymorphism? Nope. Inheritance? Nope. Modules are pretty weak candidates for "objects".


问:
Heaps: Why is there a tradeoff between amount of space occupied (fragmentation), and speed at which operations are carried out?
Apparently, the two major judging criteria of the effectiveness of heaps are (1) how much we can minimize the amount of space it takes up and (2) how fast operations on the heap can be carried out, eg, malloc and free

But I was wondering how these two criteria were related, namely, why there is a 'tradeoff' and why a faster heap makes it difficult for a smaller heap in size.

Also, why does a particular allocation alignment need to exist (for instance 8- or 16- byte) when then word size is clearly 4 bytes? If you allocate an int and a double, can't it just be:

allocate int at location 0

then

allocate double at location 4

(and then somehow keep track of the fact that a double-word is located at this location)? Then we would eliminate a LOT of fragmentation within the heap...

答:
Fragmentation comes from memory that is unusable. Dynamic allocation is similar to playing Tetris - if you play fast you end up with holes (fragmentation), and you can't predict what type block is going to fall down next. With dynamic allocation, you can't predict when and what memory is going to be freed - imagine playing Tetris where blocks disappear randomly! Also keep in mind that dynamic allocation may require allocating variable-sized blocks - Tetris would involve polynominos instead of tetrominos!

A bit on dynamic allocation techniques:

The way you described is fixed-size block allocation. It is usually implemented as a free list. The problem with this method is that it can't allocate different size blocks and it can lead to bad caching behavior.

One of the simplest ways to implement dynamic allocation is buddy memory allocation - implemented as a binary tree that satisfies the heap property. The problem with this method is that it has internal fragmentation. Internal fragmentation comes from using techniques that use predetermined blocks, usually powers of 2. This means that allocating 150 bytes would actually allocate a block of 256, wasting 106 bytes due to internal fragmentation.

Other methods try to minimize fragmentation, such as slab allocation. Slab allocation is primarily used for kernels, as it was designed to allocate small objects - it's not ideal for general purpose malloc.

Anyways, the point I'm getting to is that it all depends on the type of allocations you're doing. Operating systems don't know which allocation method would be best for a program, and that is why they choose one that balances speed with fragmentation. It's nearly impossible to have 0 fragmentation without constantly pushing data around, that's just the nature of dynamic allocation.


问:
How should I go about fixing code from a less-experienced programmer?
A little background: I am one of two programmers for our department of 10 people (the rest are artists and management). The two of us do all of the coding required to make things flow well, and develop any projects that come up. I've been programming for about 4 years now, where this is his first "real" job (as he puts it). We generally are working on different projects at any point in time.

A couple months ago I developed a (by no means perfect) set of classes that were to be used for a later project. A large portion of that project was delegated to him (for billing reasons) to design and program a GUI interface. Since he was new, I helped a bit with the designing, and said to ask for help if he needed it with the rest. He finished up the interface a few weeks ago, which he demo'd to show that it worked, although a little slow.

The next part of that project has started which I'm working on. I opened up the interface to start with the next steps, and immediately ran into issues (a little slow was a little understatement, errors on common actions, etc.). I looked in to the code for a few issues and am finding O(n^n) on calls that should be O(n), type assumptions with no error checking (it's in Python), references to the GUI added to the original code, and so on.

Now, I definitely would like to teach him what was wrong and how to fix it, but he's already moved on to his next project, and this was a few weeks ago. I'm afraid me saying "Go back and do it right!" (with help of course) is too harsh, and we still have other projects to get done in the meantime. Should I just fix the code myself for now and try to catch things in the future?

答:
Sounds like instituting some sort of code review policy might be beneficial on multiple levels. Some immediate benefits:

You can directly influence the quality of his code before code is committed thus keeping the code base quality high

Keeps you from making similar mistakes that another set of eyes may catch

In the absence of coding guidelines, reviews naturally lead to consistency in coding style

Knowledge sharing. If there's only two of you and one gets hit by a bus...

Now when you go ahead and start cleaning up his code, use that as a teaching exercise when you seek a review of this code. You will be getting your stuff reviewed, and he may learn how to do it better next time.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
The Internet

As Joel Spolsky said, "The internet should be as freely available as air."


答:
Never ever never fix their code, otherwise they won't learn anything other than if they makes mistakes you'll catch them and fix them. The task isn't done until it's done. I got really lucky when I started professional and my direct supervisor rechecked everything I committed, and if there was a better solution or I'd made a silly mistake would tell me, which meant my skills got better, which meant I improved quicker and developed a harder skin.

Letting it slide will breed bad habits, correcting now will make them cope better with criticism, and to triple check before claiming it's done.

Title: How should I go about fixing code from a less-experienced programmer?

Body:
A little background: I am one of two programmers for our department of 10 people (the rest are artists and management). The two of us do all of the coding required to make things flow well, and develop any projects that come up. I've been programming for about 4 years now, where this is his first "real" job (as he puts it). We generally are working on different projects at any point in time.

A couple months ago I developed a (by no means perfect) set of classes that were to be used for a later project. A large portion of that project was delegated to him (for billing reasons) to design and program a GUI interface. Since he was new, I helped a bit with the designing, and said to ask for help if he needed it with the rest. He finished up the interface a few weeks ago, which he demo'd to show that it worked, although a little slow.

The next part of that project has started which I'm working on. I opened up the interface to start with the next steps, and immediately ran into issues (a little slow was a little understatement, errors on common actions, etc.). I looked in to the code for a few issues and am finding O(n^n) on calls that should be O(n), type assumptions with no error checking (it's in Python), references to the GUI added to the original code, and so on.

Now, I definitely would like to teach him what was wrong and how to fix it, but he's already moved on to his next project, and this was a few weeks ago. I'm afraid me saying "Go back and do it right!" (with help of course) is too harsh, and we still have other projects to get done in the meantime. Should I just fix the code myself for now and try to catch things in the future?


问:
Is there a common capitalization convention in C++?
I do a lot of work in Python and Java, and both those languages have fairly common (though not universal) conventions on how capitalization should be used in identifiers: both use PascalCase for class names and ALL_CAPS for "global" constants, but for other identifiers a lot of Java code uses mixedCase whereas a lot of Python code uses underscore_delimiters. I know that no language or library enforces any particular capitalization, but I've found that when I stick to the standard conventions for the language I'm using, my code seems much more readable.

Now I'm starting a project in C++, and I'd like to apply the same idea. Is there any most common convention for capitalization that I should know about?

答:
Well, there's Systems Hungarian which is really common even now, but I'd rather cut my own throat than recommend it. Apps Hungarian is better as its annotative marks are truly indicative of semantics, though I feel that it's a little too keen on abbreviations when a short word would do. (To use the example from that Wikipedia page, why use rw for row when row is only one character longer? It's not like there's a global vowel shortage.)

Realistically though, the most important thing is to follow the conventions of the people you are working with. Really. Most conventions work well enough, especially if used consistently. Inconsistency is worst (even more so than Systems Hungarian, which I hate). And if you're on your own, use whatever you want.


答:
Is there any most common convention for capitalization that I should know about?

C++ is based on C, which is old enough to have developed a whole bunch of naming conventions by the time C++ was invented. Then C++ added a few, and C hasn't been idle with thinking of new ones either. Add to that the many C-derived languages, which developed their inventor's C naming conventions further, to the point where they back-fertilized on C and C++... In other words: C++ hasn't one, but many of such conventions.

However, if you are looking for the one naming convention, you might as well look at the standard library's naming convention, because this is the single one that all C++ developers will have to know and be used to.

However, whatever you use the most important rule is: Be consistent!

Interestingly, while I started out with a mix of PascalCase and camelCase, and was involved in numerous projects with even more numerous naming conventions, over the years I find I got stuck more and more with the standard_library_convention. Don't ask me why.

Title: Is there a common capitalization convention in C++?

Body:
I do a lot of work in Python and Java, and both those languages have fairly common (though not universal) conventions on how capitalization should be used in identifiers: both use PascalCase for class names and ALL_CAPS for "global" constants, but for other identifiers a lot of Java code uses mixedCase whereas a lot of Python code uses underscore_delimiters. I know that no language or library enforces any particular capitalization, but I've found that when I stick to the standard conventions for the language I'm using, my code seems much more readable.

Now I'm starting a project in C++, and I'd like to apply the same idea. Is there any most common convention for capitalization that I should know about?


答:
From what I've seen, it varies between projects.

Embedded underscores are probably more traditional/more commonly used in C on Unix. The standard library follows this as well, so it should almost certainly be treated as the default, to be used unless there's enough existing code using another convention to absolutely force using that other convention.

Windows (for one example) uses camel case for most of its functions, so quite a few people who develop for Windows do the same. This is also fairly common among people who are really more accustomed to other languages, and attempt to treat C++ as if it were just an odd variant of something else.


答:
This reference describes a naming convention that's pretty similar to ones I've seen used with success in at least three companies I've worked for in the past.

Contrary to an earlier answer, I would avoid following the C++ Standard Library's naming convention in my own code, if for no other reason than to avoid name collisions with the Standard Library.

This previous SO answer on a related topic may also be of interest: https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier


答:
Let's first agree that ALL UPPERCASE is an eyesore and should be minimized.

In C and C++ it's therefore used as a convention for macros, and macros only, because macros are equally ugly, not to say evil.

Early C didn't have const, so constants had to be expressed as macros. Also, in those early days programs were much shorter, so that the practices that are ungood today could be used (e.g. IIRC Brian Kernighan wrote code with lots of non-uppercase macros). And also, in those days keyboards that didn't have lowercase letters did exist; I used one such, on the Norwegian Tandberg EC-10 computer, about 1980 or 1979 I think it was.

So, Java picked up the uppercase convention for constants from early C. Meanwhile, and perhaps even before that (I'm not sure of the chronology here), C got constants. However, while of course some/many C programmers were stuck in the earlier convention-by-necessity of constants as uppercase macros, C++ programmers were more sensible.

The big problem nowadays is when people are taught Java first, or C (with conventions from the middle ages) first, and then come to C++, taking that foul uppercase convention with them.

So,

```<code>    int const answer = 42;    // Nice, good, OK.
    const int ANSWER = 0x2A;  // Ouch!
    #define COMPANYNAME_ANSWER 052  // Oh kill me, please.
</code>```

Well you might have thought I mentioned uppercase-only keyboards in jest. Oh no. Because that's merely the oldest, most archaic technology limitation that has driven naming conventions, or at least affected how wrong/right they have seemed. Next, there was the problem of 7-bit serial transmission, which caused corresponding problems with the character codes (newspeak character encodings) used, which meant you had to restrict yourself to the letters of the English alphabet, A through Z.

Actually I recommend still doing that. That's where we're at! We haven't got further.

At the moment, as of 2011, standard C++ supports general Unicode in names (and has done so since 1998), while actual C++ implementations do not. In particular the g++ compiler is national character challenged. It stems from that dark ages technological limitation.

So,

```<code>    double blueberryJamViscosity  = 0.0;    // OK
    double blåbærsyltetøyViskositet = 0.0;  // Ouch!
</code>```

Finally, on the subject of underscores versus interspersed uppercase letters,

Reserve an easily recognized form for type names.

Reserve ALL UPPERCASE for macros.

Be consistent.

I think that's that, really, except for rules like "generally avoid single-letter name except for (loop, template param, blah blah)", and "avoid using l, easily confused with 1" and "avoid uppercase O, easily confused with 0". Also, of course, avoid using reserved names like starting with underscore followed by uppercase, containing two successive underscores, or starting with underscore and being in the global namespace.

Cheers & hth

Body:
Let's first agree that ALL UPPERCASE is an eyesore and should be minimized.

In C and C++ it's therefore used as a convention for macros, and macros only, because macros are equally ugly, not to say evil.

Early C didn't have const, so constants had to be expressed as macros. Also, in those early days programs were much shorter, so that the practices that are ungood today could be used (e.g. IIRC Brian Kernighan wrote code with lots of non-uppercase macros). And also, in those days keyboards that didn't have lowercase letters did exist; I used one such, on the Norwegian Tandberg EC-10 computer, about 1980 or 1979 I think it was.

So, Java picked up the uppercase convention for constants from early C. Meanwhile, and perhaps even before that (I'm not sure of the chronology here), C got constants. However, while of course some/many C programmers were stuck in the earlier convention-by-necessity of constants as uppercase macros, C++ programmers were more sensible.

The big problem nowadays is when people are taught Java first, or C (with conventions from the middle ages) first, and then come to C++, taking that foul uppercase convention with them.

So,

    int const answer = 42;    // Nice, good, OK.
    const int ANSWER = 0x2A;  // Ouch!
    #define COMPANYNAME_ANSWER 052  // Oh kill me, please.

Well you might have thought I mentioned uppercase-only keyboards in jest. Oh no. Because that's merely the oldest, most archaic technology limitation that has driven naming conventions, or at least affected how wrong/right they have seemed. Next, there was the problem of 7-bit serial transmission, which caused corresponding problems with the character codes (newspeak character encodings) used, which meant you had to restrict yourself to the letters of the English alphabet, A through Z.

Actually I recommend still doing that. That's where we're at! We haven't got further.

At the moment, as of 2011, standard C++ supports general Unicode in names (and has done so since 1998), while actual C++ implementations do not. In particular the g++ compiler is national character challenged. It stems from that dark ages technological limitation.

So,

    double blueberryJamViscosity  = 0.0;    // OK
    double blåbærsyltetøyViskositet = 0.0;  // Ouch!

Finally, on the subject of underscores versus interspersed uppercase letters,

Reserve an easily recognized form for type names.

Reserve ALL UPPERCASE for macros.

Be consistent.

I think that's that, really, except for rules like "generally avoid single-letter name except for (loop, template param, blah blah)", and "avoid using l, easily confused with 1" and "avoid uppercase O, easily confused with 0". Also, of course, avoid using reserved names like starting with underscore followed by uppercase, containing two successive underscores, or starting with underscore and being in the global namespace.

Cheers & hth


答:
C, just like C++, has the capability of providing Data Abstraction, which is one idiom of the object-oriented-programming paradigm that existed before it.

C structs can have data (and that's their main purpose)

C structs can also define function pointers as data

C structs can and often have a set of functions associated with them, just like methods, only the this pointer is not passed implicitly, but you must specify it explicitly as the first argument to each method designed to handle the specified struct. C++ does this automatically for you, both when you define and call class/struct methods.

OOP in C++ extends the means to abstract data. Some say it's harmful, while others consider it a good tool when used correctly.

C++ makes the this pointer implicit by not requiring the user to pass it into "methods of the class/struct" as long as the type can be (at least partly) identified.

C++ lets you restrict access to certain methods (class functions), and hence allows for more "defensive programming" or "idiot-proofing".

C++ encourages abstractions by providing stronger type-safety by introducing

The new operator instead of malloc + cast

Templates instead of void pointers

Inline functions receiving typed-values instead of macros

Built in Polymorphism which you don't have to implement yourself, that lets you create abstraction hierarchies, contracts and specializations.

However, you'll find many C "hackers" preaching for how C is perfectly capable of just the right amount of abstraction and how the overhead created by C++ only distracts them from solving the actual problem.

Inefficient abstracted programming models where two years down the road
     you notice that some abstraction wasn't very efficient, but now all
     your code depends on all the nice object models around it, and you
     cannot fix it without rewriting your app. -- Linus Torvalds

Others tend to look at it in a more balanced way, accepting both the advantages along with the disadvantages.

C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off. -- Bjarne Stroustrup


答:
Can we infer that the project "works" and was done in a reasonable amount of time (albeit with some egregious but fixable design issues)? If so, it is in a lot better shape than many projects I've seen over the years.

I think that more communication would help your team-- and this could be done with regular code review.

It is good that you're sensitive to being "too harsh" and I think you'll keep that in mind that code review doesn't have to be a demoralizing hot-seat experience where the junior folks get grilled and scrutinized. It can also be a way for senior developers to demonstrate good practices and for everybody to gain trust in each other by being polite and friendly even in the presence of "mistakes".

People learn well when they see what really good stuff looks like. This is better than systematically pointing out every little flaw. The O(n^n), however, should be gently and constructively pointed out.


问:
Should a developer argue against unnecessary or harmful features?
What is a good attitude from developers when discussing new features, and namely, non critical/questionable features?

Say you are developing some sort of Java like language, and the boss says: "We need pointers so that developers could fiddle with object memory directly!"

Should the developer shoot down the idea because it adds unimaginable complexity and security vulnerabilities, or should he do what's asked?

This may not be a good example, but what about things that are more in a gray area, like adding buttons that break workflow, or goes against internal structure of the program, etc.?

What is the optimal "can do" vs. "can't do" distribution for a regular programmer?

EDIT: The question is not about a bad boss :D

I was more interested how do people approach new problems that add a noticeable amount of problems while maybe being marginally useful.

Should the general attitude be:

yes we'll do it, screw the complexity

maybe

no, the general rework, and implications don't justify the change

What should be the reaction of a good developer?

答:
This is almost a day to day task for me, and in fact I'm glad it is.

If you have the change to give your opinion on whether certain requirement should or should not be part of the application, non technical persons will expect you to fill in with your technical knowledge (e.g. "using pointers would make the application unstable" or "using a GET parameter for X purpose is a security risk"). Technical fellows would also appreciate your feedback on some specific advantage or disavantage they may not have thought about.

Of course, it is harsh when everyone wants feature X and you end up saying "it may not be good", but in the end, everyone is trying to make a secure, robust and stable application (maintainable, flexible, etc...) and every voice should count.

Answering your question, its not part of the job of a developer (which is, to develop), but it is an "extra" that delivers quality and team work.


问:
Is hungarian notation a workaround for languages with insufficiently-expressive static typing?
In Eric Lippert's article What's Up With Hungarian Notation?, he states that the purpose of Hungarian Notation (the good kind) is to

extend the concept of "type" to encompass semantic information in addition to storage representation information.

A simple example would be prefixing a variable that represents an X-coordinate with "x" and a variable that represents a Y-coordinate with "y", regardless of whether those variables are integers or floats or whatever, so that when you accidentally write xFoo + yBar, the code clearly looks wrong.

But I've also been reading about Haskell's type system, and it seems that in Haskell, one can accomplish the same thing (i.e. "extend the concept of type to encompass semantic information") using actual types that the compiler will check for you. So in the example above, xFoo + yBar in Haskell would actually fail to compile if you designed your program correctly, since they would be declared as incompatible types. In other words, it seems like Haskell's type system effectively supports compile-time checking equivalent to Hungarian Notation

So, is Hungarian Notation just a band-aid for programming languages whose type systems cannot encode semantic information? Or does Hungarian Notation offer something beyond what a static type system such as Haskell's can offer?

(Of course, I'm using Haskell as an example. I'm sure there are other languages with similarly expressive (rich? strong?) type systems, though I haven't come across any.)

To be clear, I'm not talking about annotating variable names with the data type, but rather with information about the meaning of the variable in the context of the program. For example, a variable may be an integer or float or double or long or whatever, but maybe the variable's meaning is that it's a relative x-coordinate measured in inches. This is the kind of information I'm talking about encoding via Hungarian Notation (and via Haskell types).

答:
Correct!

Outside of totally untyped languages such as Assembler, Hungarian notation is superfluous and annoying. Doubly so when you consider that most IDEs check type safety as you, er, type.

The extra "i" "d" and "?" prefixes just make the code less readable, and, can be truly misleading - as when a "cow-orker" changes the type of iaSumsItems from Integer to Long but doesn't bother refactoring the field name.

ContentLicense: CC BY-SA 4.0


问:
What do you consider to be the prime cause of software defects (and how to minimize them)
I define defect as :

"something within the application design or code which prevents it functioning as per requirements."

I'm looking for ideas about the causes of defects, eg the human factor, lack of testing, lack of prototyping, and possible ideas to mitigate these.

答: Another thing which should be mentioned is not having an outsider test. When the developer writes the tests and runs them, he only tests his interpretation not the actual requirement.  While unit test written by the devs are useful to catch some bugs, most bugs will have passed these tests but not be what the user wants or needs. Any software not tested by someone other than the developer is not tested (And I don't mean just running the developer's tests).</p>


答:
I realize that the phrase "Hungarian Notation" has come to mean something different that the original, but I'll answer "no" to the question. Naming variables with either semantic or computational type does not do the same thing as SML or Haskell style typing.  It's not even a bandaid.  Taking C as an example, you could name a variable gpszTitle, but that variable might not have global scope, it might not even constitute a point to a null-terminated string.

I think the more modern Hungarian notations have even bigger divergence from a strong type deduction system, because they mix "semantic" information (like "g" for global or "f" for flag) with the computational type ("p" pointer, "i" integer, etc etc.) That just ends up as an unholy mess where variable names have only a vague resemblance to their computational type (which changes over time) and all look so similar that you can't use "next match" to find a variable in a particular function - they're all the same.

Title: Is hungarian notation a workaround for languages with insufficiently-expressive static typing?

Body:
In Eric Lippert's article What's Up With Hungarian Notation?, he states that the purpose of Hungarian Notation (the good kind) is to

extend the concept of "type" to encompass semantic information in addition to storage representation information.

A simple example would be prefixing a variable that represents an X-coordinate with "x" and a variable that represents a Y-coordinate with "y", regardless of whether those variables are integers or floats or whatever, so that when you accidentally write xFoo + yBar, the code clearly looks wrong.

But I've also been reading about Haskell's type system, and it seems that in Haskell, one can accomplish the same thing (i.e. "extend the concept of type to encompass semantic information") using actual types that the compiler will check for you. So in the example above, xFoo + yBar in Haskell would actually fail to compile if you designed your program correctly, since they would be declared as incompatible types. In other words, it seems like Haskell's type system effectively supports compile-time checking equivalent to Hungarian Notation

So, is Hungarian Notation just a band-aid for programming languages whose type systems cannot encode semantic information? Or does Hungarian Notation offer something beyond what a static type system such as Haskell's can offer?

(Of course, I'm using Haskell as an example. I'm sure there are other languages with similarly expressive (rich? strong?) type systems, though I haven't come across any.)

To be clear, I'm not talking about annotating variable names with the data type, but rather with information about the meaning of the variable in the context of the program. For example, a variable may be an integer or float or double or long or whatever, but maybe the variable's meaning is that it's a relative x-coordinate measured in inches. This is the kind of information I'm talking about encoding via Hungarian Notation (and via Haskell types).


问:
"sell" coding my next project in an unfamiliar language
I want to code my next work project in a language I'm unfamiliar with (python). I can think of plenty of reasons from my point of view why its a good idea (not least of all because it sounds fun). However my manager will probably ask me why. I'm a little stumped on the advantages from his point of view.

EDIT: I normally code in C#

EDIT2 My reasons for wanting to code in another language;

It will make an easy project much harder so I will learn more and it will be more interesting

I have just read a book on python. I want the chance to apply it in a business application so I properly understand it

It will increase my skill set and make me more employable

Python looks fun

答:
It sounds like you just want to "have fun" on the company's time.

Choosing a language with no compelling advantages to solving the problem at hand, taking longer to deliver and leaving a support nightmare behind you.  What is there for your manager to like?

You have no justification for doing this.  If you want to play with a new language, fine, but do it in your own time before you try to convince your boss to let you use it and pick a project / language combination that actually adds value.

To give a counter-example:-

I once used PERL to automatically do some conversion of a large Delphi codebase.  I had already spent some time playing with PERL at home, the code did not to be supported beyond the end of the project and the RegExp functionality built into PERL made me several times more effective than writing the same functionality in Delphi even though my PERL knowledge was quite limited.