答:
Debugging is a very useful tools for inspecting the state of the objects and variables in your code at run time.

As previously mentioned in the answers above, debugging is extremely helpful, but there are some cases where it is limited.

In my experience, I find using the debugger to be very useful because it helps to reveal false assumptions that I was making about the state of my code.  Some people aren't as astute at reading through the code to find a bug, so debugging can help in revealing false assumptions that you or another developer made about the state of the code.

Maybe you expect that a parameter will never be null when passed to a method, so you never check for that case and carry on in the method as if that parameter will never be null.  The reality is that parameter will end up being null at some point even if you set as a pre-condition to the method that the parameter should never be null.  It always will happen.

In contrast to debuggers' usefulness in the aforementioned examples, I find it difficult and somewhat not useful to use when multi-threading (i.e., concurrency, asynchronous processing) is involved.  It can help, but it is easy to lose your orientation in the multi-threaded fog when the debugger's breakpoints are being hit in one thread at point A and a completely separate thread at point B.  The developer is forced to push the new breakpoint "thought process" on the top of his brain's "stack" and orient himself to the code at the point of the new breakpoint.  After the relevancy of breakpoint B decreases, the developer then switches back to the first breakpoint, and has to recall what he/she was looking out for before the trigger of breakpoint B.  I know that this may be a confusing explanation, but my point in this paragraph is that debugging where concurrency is used can be a very A.D.D. (Attention Deficit Disorder) process, and so it may be more difficult to remain productive in your debugging thought pattern.

Also the unpredictability of concurrent code can further distract the developer in debugging concurrent code.

In conclusion, in my honest opinion:

Debugging when concurrency is used   =    increased tendency to lose focus of "debugging thought pattern"

and

anytime else    =    increased debugging productivity b/c your attention isn't interrupted by unexpected breakpoints (unexpected due to race conditions).


问:
Building a route creator
Ok, already up front, I'm going to tell you, that this is a bonus task for Data structure course I'm taking. That should take care of all the questions whether or not this is for a homework.

Route creator

I have a task, where a company has to create a route for a given data set. The data set can be input for every operation and in the end, it should print out the optimum route. The conditions are like this:

Streets can only be directed North-South or East-West, effectively making every angle between 2 streets in 90 degrees.

The data set includes streets, junctions and places to pick client and where to drop him off, as well as the starting place for the car.

My problem is, that I'm having trouble thinking of the correct data structure way to do this.
What came up first from the top of my head was a directional graph. In theory, it should fit perfectly

Streets are input up front with numeric identificators

A node represents junction and is represented by the id's of the streets

An edge between 2 nodes represents a piece of street and has length

Places of interest are effectively a sub-class of Junction nodes therefore they have distance from the one node to another.

Best route would then be calculated by finding the shortest path from the starting place of the car to the starting place of the client + shortest path from the starting place of the client to the ending place of the client + shortest path from the ending place of the client to the starting place of the car.

Is my thinking in this matter even remotely correct? I am finding this quite difficult to image with any other data structure than a directed graph, but maybe I'm just limiting my options with this thinking.

答:
There is no doubt that a road network and routefinding algorithm is best modeled with a graph and using A*, Dijkstra's algorithm, or some variation of those for searching.

In your case, no doubt the intersections should be modeled as nodes and the roads as edges. As the author of a commercial GPS package, I model the starting point of each road as a node (so a junction of three roads has three nodes); this more complex model allows you to count turn costs (especially, making U-turns expensive) and turn restrictions.

If all roads have the same speed limit or you want to find the shortest distance, A* is a good algorithm, but if h(x) isn't close enough to the actual path cost, A* routing may offer no speed advantage over the simpler Dijkstra algorithm. I used A* originally, but these days I use a modified bidirectional Dijkstra algorithm, which you can think of as A* without the extra overhead of computing h(x).

The fact that all roads are located on a grid may affect the data structure you choose, but you could divide your code into two parts, one is a generic A* or Dijkstra algorithm that supports any graph regardless of how it's stored, and the other takes care of the implementation details of your data structure.

ContentLicense: CC BY-SA 3.0

Title: Building a route creator


问:
Adding more responsibilities to Activities in a flexible way
I am considering how I can add tasks to Android Activities in a flexible way. I can only use implementation inheritance for one thing in Java and I would like to use it, if I use it at all, for something else.

I think I need to draw the domain first a bit:

Activities are UI windows basically, with intrinsic lifecycle responsibilities enforced by the API. The tasks I speak of are UI-visible popovers that do some offline stuff and then disappear. They stem from AsyncTasks. The code of all of this is not a problem, I have this already, even pretty generalized with interfaces. I'm looking at further design improvements I can make.

There are many type of activities and they could all work with some types of tasks. For instance a search window would have a task that adds one of the search results, let's say it's a book, to the collection of books in the main application. It allows you to add multiple, hence the popover. A window that displays the collection has a task that lets you export a book to an external file format. It won't stop you from browsing through your collection, yet it needs to display a progress bar as it may take a while to export.

A specific Task exists as a nested class in a specific Activity. It needs to be saved away and restored along with lifecycle events: there's a onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle) for that, among others. The Activity has a list of active tasks (or just a member for one task). Some UI event will create a new task and add it to the list, a la onClick(): ATask task = new ATask(); task.execute(something);.

Here's what I have considered so far:

Implementation inheritance

Just move this task business to an abstract super class of all specific activities.

Decorator pattern

Create a TaskedActivityDecorator that would add this responsibility on any activity. The decorator would have to mimic the entire Activity interface as provided by the API, mostly passthroughs though. So this may already be a bit too heavyweight. It would also need to add the UI events/buttons that launch the task, which may not always be possible if the action is more consequential.

But the biggest problem I could come up with here is that Android uses a manifest to loosely couple all activities together. Therein you need to declare every specific activity or it can not be used. This is a problem because the decorator would work at runtime, with composition. I can't declare the decorator and add in the information that it needs to wrap a specific activity.

With Android I seem to end up with implementation inheritance a lot more than I'd like to. Hence I have too much coupling or code duplication. The activities always easily grow out to big fat classes. Am I correct to say that that is partly because of existing design choices in the Android framework, such as the manifest taking away composition solutions, or the Context object? Am I correct to say that from the get-go it cuts away a significant amount of established design patterns in key areas, including the MVC pattern.

Decorator with wrappers:

That I can't specify the decorator and the specific activity it applies to together in the manifest, doesn't mean I can't create classes that represent and arrange this composition. I could of course create many SpecificDecoratorActivity classes, that also implement the Activity interface and act like the decorator, and then wrap in the real specific activity. I'm not sure if it solves my problem though. It seems like a lot of work, a lot of rubbish classes, and takes me far from my original goal.

Strategy pattern:

If I can't skin the activity, then I'd better outsource part of its guts. This will give me yet more connections though as the activities will need to know about the Strategy. The Strategy itself however will be more lightweight as a Decorator. Yet it feels not so much like Strategy where there is a choice of which one, but rather just moving part of the class to another class. I would call it TaskManager. And would I still pull up the strategies knowledge into an activity super class?

Any other pattern?:

Which pattern is the best choice? Don't shun your opinion on the specific Android case. No need to talk about tasks specifically.

答:
First, I don't know anything about Android development, so I was waiting for someone else to answer you, but since you haven't gotten a lot of responses:

What about the Bridge pattern?  This isn't the canonical case described in Design Patterns, but it sounds like it might fit, since what you want is to have separate hierarchies with implementation inheritance (one for tasks and one for activities).

This is similar to what you discussed as a strategy pattern, and yes, it is moving part of the class to another class, but to a new class that doesn't have the limitations (i.e., the manifest) of the old.  I'm not sure this gives you more connections - a reference seems a weaker connection than a nested class.

As far as putting the strategies knowledge into an activity super class, you could, but you did state that you would rather use implementation inheritance for something else.  If so you could put into an interface instead.


问:
What's the benefit of avoiding the use of a debugger?
Over the course of my career, I've noticed that some developers don't use debugging tools, but do spot checking on erroneous code to figure out what the problem is.

While many times being able to quickly find errors in code without a debugger is a good skill to have, it seems it's less productive to spend a lot of time looking for issues when a debugger would easily find little mistakes like typos.

Is it possible to manage a complex without a debugger? Is it advisable? What benefits are there to be had by using "psychic debugging?"

答:
With good unit tests, and exceptions that provides you the backtrace, you rarely have to use a debugger.

The last time I used a debugged was when I got a core file in some legacy application.

Am I being a "debbuger minion" or are these guys being "too hardcore"?

Neither. They are just kind of people who likes to make their life harder then it should be.


问:
Approaches against code base becoming uniformly slow
We are working on a moderately-sized C++ code base (10Mloc) which through our optimization efforts is becoming uniformly slow.

This code base is a set of libraries which we combine to put them to work. When the general framework of how these libraries communicate was developed there was some emphasis on performance and later on, when more parts where added, the general framework wasn't changed much. Optimization was done when needed and as our hardware evolved. This made expensive early decision apparent only much later. We are now at a point where further optimizations are much more expensive since they would require rewriting large parts of the code base. We find ourselves approaching an undesirable local minimum since we know that in principle the code should be able to run much faster.

Are there any successful methodologies which help to decide what turns to take over the evolution of a code base towards a globally optimally performing solution which aren't easily confused by easy optimization opportunities?

EDIT

To answer the question how we currently profile:

We really only have 2 different scenarios how this code can be used, both embarrassingly parallel. Profiling is done both with wall clock time averaged over a large sample of inputs and more detailed runs (instruction costs, branch mispredictions and caching issues). This works well since we run exclusively on our extremely homogeneous machines (a cluster of a couple thousand identical machines). Since we usually keep all our machines busy most of the time running faster means we can look at additional new stuff. The issue is of course that when new input variations show up, they might get a late-comer penalty since we removed most obvious micro-inefficiencies for the other use cases, thus possibly narrowing down the number of "optimally running" scenarios. The current answers rightly suggest to separate data and algorithms so this becomes easier to adjust.

答:
This made expensive early decision apparent only much later. We are now at a point where further optimizations are much more expensive since they would require rewriting large parts of the code base.

When you start this rewrite you have to do several things differently.

First.  And most important.  Stop "optimizing".  "Optimization" doesn't matter very much at all.  As you've seen, only wholesale rewrite matters.

Therefore.

Second.  Understand the implications of every data structure and algorithm choice.

Third.  Make the actual choice of data structure and algorithm a matter of "late binding".  Design interfaces which can have any one of several implementations used behind the interface.

What you're doing now (rewriting) should be much, much less painful if you've got a set of interfaces defined that allows you to make a wholesale change to data structure or algorithm.


答:
Hate to generalize, but many programmers I have met think there is only one way to solve a problem (their way). It is easy to assume that every possible test has been thought of. A different perspective can be very valuable.

Programming by trial and error can come up with some great new approaches, and catch things others have missed.

The downside, usually takes much longer.

Title: What's the benefit of avoiding the use of a debugger?

Body:
Over the course of my career, I've noticed that some developers don't use debugging tools, but do spot checking on erroneous code to figure out what the problem is.

While many times being able to quickly find errors in code without a debugger is a good skill to have, it seems it's less productive to spend a lot of time looking for issues when a debugger would easily find little mistakes like typos.

Is it possible to manage a complex without a debugger? Is it advisable? What benefits are there to be had by using "psychic debugging?"


答:
Your best guide to the practice of debugging is Steve McConnel's book Code Complete. Chapter 23 covers debugging in detail, and I will distill a few points from it.

Understanding the problem is important, and use of the debugger is not a substitute for it.

Guessing is a bad approach to debugging. If your colleagues are really using guesswork, rather than thinking about the problem, then they are doing a bad job. Guesswork means sticking random print statements in the code and hoping to find something useful.

If your colleagues genuinely don't know how to use a debugger (rather than choosing not to use one) then yes, they are incompetent, just like someone who doesn't know the syntax of the language they are supposed to be using.


问:
How to use a MessageBox using the MVVM pattern?
I am implementing a UI application using the MVVM design-pattern.

The thing is, sometimes when you detect that something is wrong with data that was inputted by the user, you'd like to notify him somehow.

The solution I used so far was to have a "messaging framework" which allows me to basically show messages in a ListView I integrate within the window.

However, sometimes the windows get a bit "overloaded" with graphical elements, and I would like to be able to show the messages in a message box (basically a modal window).

As the ViewModel is not supposed to be aware of anything about the UI, I cannot instantiate any window "explicitly".

Ideally, this modal window would also use the MVVM pattern and hence I would implement a ViewModel for that window, which would be instantiated within the "main" windows's ViewModel, and passed to the modal window through the DataContext.

I would like to have a "simple" example of how to do such thing? Or should this approach be banned from an MVVM application?

EDIT:

Would the use of the Unity Framework be something you recommend?

答: Make it part of your messaging framework.  That is, your message could have an attribute such as UserMustAcknowledge.  When the View of the messaging framework sees that, it kicks off a message box.


问:
From where did the symbols *args and **kwargs in Python originate?
I know that *args and **kwargs are ways to feed more arguments into a function in Python.

I am wondering where these terms stem from. Why have all the asterisks in the beginning? What does the kw in kwargs stand for?

答:
The "kw" stands for Key Word because the dictionary that you pass in is expanded to a sequence of key-word pair arguments. As to "Why have all the asterisks in the beginning?" I ask you, why not have them?

My hypothesis as to why the * characters were chosen is that they frequently have a wildcard meaning (e.g., in regular expressions or globing). This is just guess-work though and I have nothing to document that.


问:
How do you code without offending?
What I mean by that is, how do you go about developing on a code base you share with developers who have been working on it for years and are very familiar with it?

I don't want to step on anyones toes, but I get not so subtle complaints about the way I do things, whether it be how I whitespace my code, or how frequently I checkin to SVN (too often). So while I can change those things easily -- I want to be a better team developer in general.

I'm not sure what to do, other than ask, but maybe you guys have some thoughts I could put to practice.

UPDATE

There isn't any style guide to speak of -- it's just people aren't used to sharing the codebase. Everyone has their own little siloed code-world.

This is a perl shop, but I'm sure these apply to any language

UPDATE 2

The CTO who later became CEO was a complete megalomaniac and was the primary source of these complaints. If you didn't do things exactly how he liked, whether it was using a Mac, or Emacs, or 4 tab spaces instead of 2, or dress a certain way, you were inferior. It was a horrific situation that I tried to correct, but the only correct answer for me was leaving.

I am convinced that this was an instance of bullying in a workplace, and subsequently, I'm more aware of what might be subtle bullying and inappropriate behavior in a work environment.

To any developer looking for answers to a situation like this, leave immediately. You can't teamwork your way out of a bad team situation.

答:
The best thing you can do is to follow the advice they give you. There's no way to tell ahead of time what they want. Unless you're psychic.

However, i would suggest that as people give you advice, you document it. Do you have a wiki? If so, use it. If not, a text file checked in with the source code might be a good idea. Build up a well-organised programming guide. It will help you remember how to do things, and if someone contradicts earlier advice you've been given, it gives you a reference point to discuss the inconsistency. Plus, when the next person joins the team, they won't have to go through what you're going through.

I would suggest you don't attribute the advice in the document to individuals (so "code blocks should be indented by three spaces", not "Bill told me that code blocks should be indented by three spaces"). However, if you can record that information in an unobtrusive way (eg in the commit comment, write "added rule about indentation based on Bill's advice"), then it might be helpful in resolving contradictions, because you can immediately get two points of view on something. What i'm thinking about here, really, is that if you're given contradictory advice, you need to avoid becoming a football being kicked around by two colleagues who disagree on something. It's a bit of a cover-your-arse approach, but it might be prudent.

Title: How do you code without offending?


答:
Erm, it depends on the person. Personally, I don't use debuggers that much myself. When I program micro controllers, I basically use LEDs or writing data to EEPROMs to "debug" the code on it. I don't use JTAG.

When I program software for PCs or servers, I tend to use logging and lots of console output. For C-style languages, I use preprocessor directives, and in Java I used log levels.

Since I don't use debuggers, would you say I'm doing something wrong? It's the editors jobs, to show me where I have syntactical errors, and when there's a logical error, I just have to run tests.


问:
What is inversion of control, and when should I use it?
I am designing a new system and I want to know what inversion of control (IOC) is,  and more importantly, when to use it.

Does it have to be implemented with interfaces or can be done with classes?

答:
IoC (see Inversion of Control on Wikipedia) is applicable in cases where a component can not perform a task entirely because it doesn't have some necessary information or functionality.

The simplest example of an IoC pattern would be callback functions in C. For example you can declare the function:

```<code>void Iterator(void *list, Func* f)
</code>```

Which iterates over list applying the f function to each of it's item. The Iterator function doesn't  know how each item will be processed, you just provide a function as an argument, and it processes them.

As the previous example shows, IoC allows you to decouple your program into separate components that don't know about each other. One of the most common versions of IoC is Dependecy Injection.

In Dependency Injection each component must declare a list of dependencies required to perform it's task. At runtime a special component (generally) called an IoC Container performs binding between these components. It tries to provide values for published component dependencies.

Here is an example in pseudo-code:

```<code>class Foo
{
   <Require Boo>Constructor(Boo boo){ boo.DoSomething }
}
</code>```

In this example class Foo has a constructor that requires argument of type Boo to perform some action.

You could create an instance of class Foo using code similar to this:

```<code>MyContainer.Create(typeof Foo)
</code>```

MyContainer - is an IoC Container, which takes care of getting instance of Boo and passing it to the Foo constructor.

In summary, IoC allows you to decouple your program into separate parts. This is good because:

Components can be easily tested independently.

Program complexity can be reduced.

You can switch components to another implementation.

However in some cases, IoC can make code harder to understand.

If you want to see good example of real-world usage of IoC, have a look at Mircosoft Composite UI Application Block and CompositeWPF

I hope my explanation helps you.

Regards,

aku

OwnerDisplayName: Jedi Master Spooky

Body:
IoC (see Inversion of Control on Wikipedia) is applicable in cases where a component can not perform a task entirely because it doesn't have some necessary information or functionality.

The simplest example of an IoC pattern would be callback functions in C. For example you can declare the function:

void Iterator(void *list, Func* f)

Which iterates over list applying the f function to each of it's item. The Iterator function doesn't  know how each item will be processed, you just provide a function as an argument, and it processes them.

As the previous example shows, IoC allows you to decouple your program into separate components that don't know about each other. One of the most common versions of IoC is Dependecy Injection.

In Dependency Injection each component must declare a list of dependencies required to perform it's task. At runtime a special component (generally) called an IoC Container performs binding between these components. It tries to provide values for published component dependencies.

Here is an example in pseudo-code:

class Foo
{
   <Require Boo>Constructor(Boo boo){ boo.DoSomething }
}

In this example class Foo has a constructor that requires argument of type Boo to perform some action.

You could create an instance of class Foo using code similar to this:

MyContainer.Create(typeof Foo)

MyContainer - is an IoC Container, which takes care of getting instance of Boo and passing it to the Foo constructor.

In summary, IoC allows you to decouple your program into separate parts. This is good because:

Components can be easily tested independently.

Program complexity can be reduced.

You can switch components to another implementation.

However in some cases, IoC can make code harder to understand.

If you want to see good example of real-world usage of IoC, have a look at Mircosoft Composite UI Application Block and CompositeWPF

I hope my explanation helps you.

Regards,

aku

OwnerDisplayName: aku

ContentLicense: CC BY-SA 2.5


答:
Basically IoC/DI will allow you to define which implementation you're using once, and keep a static copy of your container to reference each time you want to reference it.

The Wikipedia will probably help you, but I wanted to reference your second part - yes, dependency injection can be done for classes (ie, every time this class type needs to be passed to a method, use this class), but it's better to use interfaces, because that way you can change which version of a provider, repository, etc you're using just by re-referencing it in your setup.

E.g. say you had an interface to read a stream in, and you had an XMLStreamReader and a SQLStreamReader implementation.  Then you can pass the reference to the interface to your methods and then in your IoC container tell it which one to use.

So, you could have public List ReadPeople(IStreamReader reader) and in your setup for your IoC container tell it, every time you expect an IStreamReader use SQLStreamReader.

Then if you change your mind later, you only need to change it in the one place (the setup of your container) and it won't matter how many methods ask for an IStreamReader, it will always get the default you told your container to serve up.

Title: What is inversion of control, and when should I use it?

Body:
I am designing a new system and I want to know what inversion of control (IOC) is,  and more importantly, when to use it.

Does it have to be implemented with interfaces or can be done with classes?

OwnerDisplayName: crucible

ContentLicense: CC BY-SA 4.0


答:
Since I dug into this myself recently, and kept all the bookmarks, the following I found invaluable for learning about IOC/DI.

Martin Fowlers Original Article on IOC/DI

Some Concepts To Know First

An excellent collection of IOC/DI Tutorials

Book on IOC/DI From Manning Press

Source and Explanation of how to create your own IOC - Cause reading source code is always the best way to understand a concept.

OwnerDisplayName: Kris Erickson


问:
How do you keep emails short but complete?
I'm the odd kind of developer that likes writing and explaining - emails, specs, you name it.  I enjoy helping people understand things deeply. I hate ping-pong communications where groups go through 30 or 40 emails, phone calls and meetings because 25% of the group misunderstood the previous dashed-off email in which the writer only half-explained their position, or was in a hurry and miswrote a critical word or left out a negative or two.

This trait is great for documentation, but my emails are long, so people simply don't read them. A couple strategies I've used are formatting long emails as attached Word documents to encourage people to view them as documentation (works surprisingly well sometimes), or trying to use more bullet points instead of free paragraphs. These strategies increase readership, but the content is still long.

Of course I want to yell and scream that complex technical topics require a lot of exposition and clarification, but that doesn't help anyone. Obviously there are tradeoffs that can be made, but I have a hard time justifying making statements that aren't clear or that will result in a million questions, misunderstandings, or added "terms and conditions" later on.

How do you keep your communications short but complete?

答:
I use fewer words, that seems to do the job quite well.

seriously, tho...

Try only explaining things that are pertinent, for example, "load a file" instead of going into detail about HOW you load the file and check for errors while doing it and etc. etc.


答: Let's say you have a validator for checking whether or not a business is valid in your system.  Your "BusinessValidator" may have a field of type AddressValidator which validates the address part of the business.  If you want to test the BusinessValidator without executing outside code (i.e. the addressValidator code) then if you have used some sort of IoC/DI in your framework you can easliy "inject" a mock addressValidator in it's place and not have to worry about testing code outside the scope of the class under test.  </p>

OwnerDisplayName: codeLes


问:
Difference between Dependency Injection (DI) and Inversion of Control (IOC)
I've been seeing a lot of references of Dependency Injection (DI) & Inversion Of Control (IOC), but I don't really know if there is a difference between them or not.

I would like to start using one or both of them, but I'm a little confused as to how they are different.

答:
Definitions

Inversion of control is a design paradigm with the goal of reducing awareness of concrete implementations from application framework code and giving more control to the domain specific components of your application. In a traditional top down designed system, the logical flow of the application and dependency awareness flows from the top components, the ones designed first, to the ones designed last.  As such, inversion of control is an almost literal reversal of the control and dependency awareness in an application.

Dependency injection is a pattern used to create instances of classes that other classes rely on without knowing at compile time which implementation will be used to provide that functionality.

Working Together

Inversion of control can utilize dependency injection because a mechanism is needed in order to create the components providing the specific functionality.  Other options exist and are used, e.g. activators, factory methods, etc., but frameworks don't need to reference those utility classes when framework classes can accept the dependency(ies) they need instead.

Examples

One example of these concepts at work is the plug-in framework in Reflector.  The plug-ins have a great deal of control of the system even though the application didn't know anything about the plug-ins at compile time. A single method is called on each of those plug-ins, Initialize if memory serves, which passes control over to the plug-in.  The framework doesn't know what they will do, it just lets them do it. Control has been taken from the main application and given to the component doing the specific work; inversion of control.

The application framework allows access to its functionality through a variety of service providers. A plug-in is given references to the service providers when it is created. These dependencies allow the plug-in to add its own menu items, change how files are displayed, display its own information in the appropriate panels, etc. Since the dependencies are passed by interface, the implementations can change and the changes will not break the code as long as the contract remains intact.

At the time, a factory method was used to create the plug-ins using configuration information, reflection and the Activator object (in .NET at least).  Today, there are tools, MEF for one, that allow for a wider range of options when injecting dependencies including the ability for an application framework to accept a list of plugins as a dependency.

Summary

While these concepts can be used and provide benefits independently, together they allow for much more flexible, reusable, and testable code to be written.  As such, they are important concepts in designing object oriented solutions.

OwnerDisplayName: Elijah Manor

OwnerDisplayName: Chuck


答: Inversion of control is a general concept, in functional languages is usually done using continuations. This let's you write an API where both sides are 'caller', and none the 'callee'.  In other, more static environments you don't have this facillity, so you need this hack to insert hints into the control flow.</p>

Title: Difference between Dependency Injection (DI) and Inversion of Control (IOC)

Body:
I've been seeing a lot of references of Dependency Injection (DI) & Inversion Of Control (IOC), but I don't really know if there is a difference between them or not.

I would like to start using one or both of them, but I'm a little confused as to how they are different.

OwnerDisplayName: Javier


答:
I do not know of a general-purpose approach to this problem, but two somewhat related approaches worked well for me in the past: for lack of better terms, I called them bunching and horizontal optimization.

Bunching approach is an attempt at replacing a large number of short, fast operations with a single, slower-running, highly specialized operation that ultimately produces the same result.

Example: After profiling one particularly slow operation of our visual rule editor we discovered no "low hanging fruit": there was not a single operation that was taking more than 2% of the execution time, yet the operation as a whole felt sluggish. However, we discovered that the editor was sending a large number of small requests to the server. Even though the editor was quickly processing the individual replies, the number of request/response interactions had a multiplicative effect, so the overall time the operation took was several seconds. After carefully cataloging the interactions of the editor during that long-running operation, we added a new command to the server interface. The additional command was more specialized, as it accepted the data required to perform a subset of short operations, explored data dependencies to figure out the final set of data to return, and provided a response containing the information needed to complete all the individual small operations in a single trip to the server. This did not reduce the processing time in our code, but it cut a very significant amount of latency due to removing multiple expensive client-server round trips.

Horizontal optimization is a related technique when you eliminate the "slowness" that is thinly distributed among multiple components of your system using a particular feature of your execution environment.

Example: After profiling a long-running operation we discovered that we make a lot of calls across the application domain boundary (this is highly specific to .NET). We could not eliminate any of the calls, and we could not bunch them together: they were coming at different times from widely different sections of our system, and the things they requested were dependent on the results returned from prior requests. Each call required serialization and deserialization of a relatively small amount of data. Again, the individual calls were short in duration, but very large in number. We ended up designing a scheme that avoided serialization almost entirely, replacing it with passing a pointer across the app domain boundary. This was a big win, because many requests from entirely unrelated classes instantly became much faster as a result of applying a single horizontal solution.

Title: Approaches against code base becoming uniformly slow

Body:
We are working on a moderately-sized C++ code base (10Mloc) which through our optimization efforts is becoming uniformly slow.

This code base is a set of libraries which we combine to put them to work. When the general framework of how these libraries communicate was developed there was some emphasis on performance and later on, when more parts where added, the general framework wasn't changed much. Optimization was done when needed and as our hardware evolved. This made expensive early decision apparent only much later. We are now at a point where further optimizations are much more expensive since they would require rewriting large parts of the code base. We find ourselves approaching an undesirable local minimum since we know that in principle the code should be able to run much faster.

Are there any successful methodologies which help to decide what turns to take over the evolution of a code base towards a globally optimally performing solution which aren't easily confused by easy optimization opportunities?

EDIT

To answer the question how we currently profile:

We really only have 2 different scenarios how this code can be used, both embarrassingly parallel. Profiling is done both with wall clock time averaged over a large sample of inputs and more detailed runs (instruction costs, branch mispredictions and caching issues). This works well since we run exclusively on our extremely homogeneous machines (a cluster of a couple thousand identical machines). Since we usually keep all our machines busy most of the time running faster means we can look at additional new stuff. The issue is of course that when new input variations show up, they might get a late-comer penalty since we removed most obvious micro-inefficiencies for the other use cases, thus possibly narrowing down the number of "optimally running" scenarios. The current answers rightly suggest to separate data and algorithms so this becomes easier to adjust.


答:
There is a difference between not needing to use a debugger and not knowing how to (or refusing to) use a debugger. The debugger is just one of many tools to use in tracking and fixing bugs. I've worked with developers who can puzzle it out in their head and others who think they can.

The best mix is to write your code so it is easy to test via unit tests, and logs the errors. Then you hope you don't need to look at the logs or use the debugger. It is kind of like buying insurance. You hopefully never need to use it, but once you run into a bug that can't be solved by rechecking the code then it is too late to add proper error handling / logging, unit tests, or learn to use a debugger.

Different tools/platforms favor different debugging techniques (debugger, logging, unit tests, etc.) As long as a developers is familiar with a few of the techniques for their platform/tool, in addition between just rechecking the code, then they may be a skilled developer, but if they only have one trick when it comes to debugging then they will eventually run into a bug they cannot find or fix.


问:
How to introduce a new pattern into an existing codebase?
In my quest to better my development skills I learn new design patterns. In sample projects or personal projects it's really easy to adapt new patterns into my code.

However at work I have a large code base that I am responsible for architecting and maintaining. This question is focused on writing consistent and maintainable code will still providing business value.

When I learn new patterns I find myself conflicted on how to proceed moving forward on an existing codebase.

Do I go back update my code to use my new pattern ?

This has the downside of not providing a ton of business value and
might not be the best way to efficiently utilize my time.

Do I move forward and use my new pattern/technique in any new code ?

This has the downside of being inconsistent, thus making my code less maintainable and setting a poor precedent for new team members.

Optionally I could just catalog the new technique in my head but not implement it. I really dislike this option though.

答:
I'm also responsible for a large code-base; when I or anyone else on the "team" - sigh I hate that word - learns a new technique we apply it immediately; as long as it results in one of the following improvements and doesn't negatively impact another.

Less lines of codes and more readable

Quicker

Uses less system resources

An improved result set

Whether you go back and change code you've already written depends entirely on whether you will actually improve them and how much time you have. You may find, and I certainly do, that there's a lot of old code that could do with improvements more than the newer stuff. Saying that I can't ever stop going back and having a little fiddle with the stuff I've personally written.

If anything I've learnt can improve my code as much as the older stuff, then there's a business case for doing it. Don't forget that you know your own code fairly well, which means any changes will be a fair amount quicker to make.


答:
Many answers, but not a mention about Heisenbug?!?!

Heisenbugs occur because common attempts to debug a program, such as
  inserting output statements or running it in a debugger, usually
  modify the code, change the memory addresses of variables and the
  timing of its execution.

I use debugger, only in the worst case (for hard-to-find bugs). Also, as per best practices that many acclaimed developers/testers have been talking about, it's good to unit test the code thoroughly. That way, you can cover most of the problems and hence there would be no need to use the debugger.


答:
Focus on what you're trying to communicate. Does each word you've used help get your message across?

Try to avoid adjectives. Avoid ranting or over-explaining. Use the most concise phrase possible - don't try to sound impressive by using long words and complex phrases where a simpler option exists. Avoid wank words.

Read 'On Writing' by Stephen King.

Title: How do you keep emails short but complete?

Body:
I'm the odd kind of developer that likes writing and explaining - emails, specs, you name it.  I enjoy helping people understand things deeply. I hate ping-pong communications where groups go through 30 or 40 emails, phone calls and meetings because 25% of the group misunderstood the previous dashed-off email in which the writer only half-explained their position, or was in a hurry and miswrote a critical word or left out a negative or two.

This trait is great for documentation, but my emails are long, so people simply don't read them. A couple strategies I've used are formatting long emails as attached Word documents to encourage people to view them as documentation (works surprisingly well sometimes), or trying to use more bullet points instead of free paragraphs. These strategies increase readership, but the content is still long.

Of course I want to yell and scream that complex technical topics require a lot of exposition and clarification, but that doesn't help anyone. Obviously there are tradeoffs that can be made, but I have a hard time justifying making statements that aren't clear or that will result in a million questions, misunderstandings, or added "terms and conditions" later on.

How do you keep your communications short but complete?


答:
There is a high risk with introducing new patterns that something might go wrong, and you'll be forced to throw away the solution. This has happened to me many times a long time before when I was junior dev; however there are habits you can chose to adapt instead which is much more effective, and it is all about good refactoring habits.

Err... habits?

Yes! Okay this'll take some time to explain, but here we go:

It may be tempting to refactor towards a pattern whenever there is downtime, unfortunately it is at these times that you'll add a design that will eventually break in the future. There is nothing wrong with refactoring towards a pattern, but there is a high risk of it ending up to be a sophisticated process of code bloat. You won't notice it until you have to tear that structure down again. I'm pretty sure we've all hit that brick wall at times: the one where your code appeared so beautiful actually made it more difficult to work with the week after.

This is from a business perspective quite wasteful "gold plating". It is better to refactor parts of the code that changes often, so that you use a pattern that makes the changes easier to implement. Thus you should think about refactoring whenever you get a ticket such as a Change Request or a Defect Report to do on a part of the system that has recurring changes. Do a design UML-sketch and estimate the time for you to refactor so it can easily deal with the repeating changes. If you want want a good first step to refactor the right way then figure out what often changes or varies in your code and encapsulate that behavior. Hence the first habit that your team should take:

Habit No. 1 — Refactor that what changes often

Design Patterns are inherently complex, so we have to be careful about applying them. The claim that design patterns are complex is heavily disputed since patterns really are meant to provide a common language between developers. Unfortunately it is very common in team settings that the team will perceive a pattern as complex. Just because you know about that pattern doesn't mean that everyone else in your team knows about it.

Let me repeat that over the common programmer ego (I sure wish someone would when I was some years younger):

Just because YOU know it, doesn't mean that EVERYONE ELSE does.

It is better to just take it little at a time, as more Change Requests come in you can easily home into a pattern that the team will be able to use. Some refactorings later and you'll end up with a useable pattern, that is easy to explain, because you did it one step at a time, and that most of the team has already seen it coming, because you did it in small steps at a time. Here are some conversational examples, just in case you need some inspiration on how small the steps would be:

"Hey, does anyone mind if I rename this method into something more descriptive?"

"So this class can be an enum instead. Makes it more type safe y'know."

"Do you mind if I introduce a parameter class for this instead?"

"This code is duplicate of this over here. Is it okay for me to put that (encapsulate) it to it's own class?"

"Lemme just let the methods return the Iterable<T> interface instead."

"Does anyone mind if I did a Visitor for this switch case instead?"

...and so on. Next thing you know, you have introduced a design pattern and everyone has learnt it in small steps and are happy about it. Hence:

Habit No. 2 — Refactor in small steps

Next habit has to do with trust and confidence. To feel confident about refactoring, you need to be sure that you don't break anything whenever you refactor and change the code. In order to reassure that you don't break behaviors, start writing new units of code together with unit tests to make sure you have code that actually works.

There is no excuse anymore to ignore unit testing really. All programming languages and environments have some kind of a unit testing functionality or a framework. If not then I hope your language is Turing Complete enough to create a testing framework yourself.

I have an anecdotal example about this

The most complex codebase I had to work with (at a well-known company that dealt with confectionary) was Javascript where I was put in charge to add a couple of new functionalities into a spaghetti mess. They didn't have any modules nor any unit tests on their own codebase, even though their code guidelines was full of wishful thinking on it all existing.

Naïve that I was and to be sure I didn't break anything I wrote some unit tests to check how the codebase worked. I could see how the inputs worked and have some validation on what the outputs became.

I then proceeded to write my own javascript modules that I did TDD-style that became well tested (with both unit and functional testing). This benefited me the most where some hairy string handling was required, and unit tests made sure I did the right thing.

When I handed over the finished result it left a lot of tech leads with their jaws dropped to the floor because here was a bloke that actually followed their coding standards and delivered code with some proof of confidence. The testing code was later given to a team that were given the task to refactor the code even further.

The habit of writing tests always pays off in the end, it will make things easier to refactor as you can see during development if you broke something. It can also be used to verify that your new code base works just as well as the old code base. Most importantly, it can be used to locate and mark bugs for other developers to fix. Do make sure you estimate enough time for you to work on it while you research the code base.

Anyhow, boiling down to a tl;dr version we have the following habit:

Habit No. 3 — For new components and classes, write unit tests

So how do you refactor towards a design pattern? Well, a lot of pattern design fashionistas tend to forget that the patterns were built upon principles. Now there are many to take in, but the basics is something you definitely need to learn:

The SOLID principles. Trust me, you'll become be a better person because of it. Also there are the two basic ones from the beginning chapter of the GoF book on Design Patterns:

"Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)

"Favor 'object composition' over 'class inheritance'." (Gang of Four 1995:20)

Once you know all of them and their applications, you'll be a design pattern guru, delivering consistently awesome and clean code. Also, when you write unit tests for your new code, you will eventually find out that well-made test code actually forces the design of your code base to follow SOLID principles. Because you follow the principles behind the patterns; next thing you know you've indadvertedly applied some kind of a pattern that fits with your code base.

Habit No. 4 — Prefer (SOLID) principles over patterns

Hope these habits puts you into the right path of applying patterns.

Title: How to introduce a new pattern into an existing codebase?

Body:
In my quest to better my development skills I learn new design patterns. In sample projects or personal projects it's really easy to adapt new patterns into my code.

However at work I have a large code base that I am responsible for architecting and maintaining. This question is focused on writing consistent and maintainable code will still providing business value.

When I learn new patterns I find myself conflicted on how to proceed moving forward on an existing codebase.

Do I go back update my code to use my new pattern ?

This has the downside of not providing a ton of business value and
might not be the best way to efficiently utilize my time.

Do I move forward and use my new pattern/technique in any new code ?

This has the downside of being inconsistent, thus making my code less maintainable and setting a poor precedent for new team members.

Optionally I could just catalog the new technique in my head but not implement it. I really dislike this option though.


答:
Do I move forward and use my new pattern/technique in any new code ?

This has the downside of being inconsistent, thus making my code less maintainable and setting a poor precedent for new team members.

Let's make an example: let's say lots of your code contains cryptic, short variable names where you always have to guess around what the meaning of those variables may be. Now you have learned the new technique of giving variables meaningful names. Do you really believe your code will get less maintainable when you immediately start to apply this technique - inconsistently with the existing codebase - throughout your new code?

(No joking, I have met developers used "consistency" as an excuse for choosing bad variable and function names).

The point is: if a pattern is useful, it should improve the maintainability of your code, even when it introduces some inconistencies. If it does not, you should question the usefulness of the pattern.


答:
The answer by @dasblinkenlight points out a very common issue, especially with large code bases (in my experience).
There may be serious performance problems, but they are not localized.
If you run a profiler, there are no routines taking enough time, by themselves, to draw attention.
(Assuming you look at inclusive time percentage that includes callees. Don't even bother with "self time".)

In fact, in that case, the actual problem was not found by profiling, but by lucky insight.

I've got a case study, for which there's a brief PDF slide show, illustrating this issue in detail and how to handle it.
The basic point is, since the code is much slower than it could be,
that means (by definition) the excess time is spent doing something that could be removed.

If you were to look at some random-time samples of the program's state, you would just see it doing the removable activity, because of the percent of time it takes.
It is quite possible the removable activity is not confined to one function, or even many functions.
It doesn't localize that way.

It's not a "hot spot".

It's a description you make of what you see, that happens to be true a large percent of time.
That makes it simple to discover, but whether it is easy to fix depends on how much re-writing it requires.

(There's a critique often made of this approach, that the number of samples is too small for statistical validity. That is answered on slide 13 of the PDF. Briefly - yes, there is high uncertainty in the "measurement" of potential savings, but 1) the expected value of that potential savings is essentially unaffected, and 2) when the potential savings $x$ is translated into speedup ratio by $1/(1-x)$, it is strongly skewed toward high (beneficial) factors.)


问:
What advantages does developing applications for smartphones have over developing the same application as a web application?
Let's take the Facebook application as an example. Why did they develop an application when the users could just access to their page and do the same? For me that represents more maintenance and more cost because for each feature added to the web application that feature will have to be added to the smartphone application as well.

So why would I want to develop more than once (for each patform iOS, Android, etc) when I could just have one web application? What benefits do I get? The only one that comes to my mind is GPS feature.

EDIT:

My question is more oriented towards business applications that are going to be used only by some members of the company, it's not about selling the application (private use). So contrary to what some answers say about that by developing as a smartphone application it will benefit from more sells because of the "smartphone stores" for me this point is not important because the application is for private use.

By developing the application as a web application it means that it can be accessed through smartphone browser and also in a PC (any capable browser), but developing as a native application would limit this to only some kind of smartphone so we would be limiting  the use.  On the other hand developing it as a web application means that in order to access the application an Internet connection must be available.

So keeping this in mind how would you convince your boss to write the application for a given smartphone platform (iOS/Android) vs developing it as a web application?

答:
Smart phones are different from normal PCs. The screen size and touchscreen make traditional webpages much more difficult to use. By creating an app for phones a better experience can be delivered to the user.

Creating an app also allows for more information to be gathered on number of active users, and information about users. This provides ways to better target advertising and more ways to advertise (I can't remember if there are adds in the FB app, but I assume there must be). An App is also really cheap advertising for a company like Facebook, a couple months of developer time is nothing compared to a guarantee that millions of people see your app in the app store.

Most data that has been released about smartphone apps has shown that most people are extremely willing to download almost anything from an app store as well, compared to downloading things from the internet to their PC, so creating an app is an effective advertising strategy and revenue generator.


答:
From a technical point of view, there are possible restrictions on what a web app can do, verses a installed app.  One great example of this is the fact you can't upload using the <input type="file"> with an iPhone.

The benefits are the same as having to build an app for different desktop operating systems, in that there aren't many, which is why the world of web applications got so much traction in the first place.  Unfortunately the current state of mobile browsers means that we are stuck with installed apps for the moment.

As mentioned in Ryathal's answer there are business reasons for doing it, such as free marketing and buzz around your new cool app.

Title: What advantages does developing applications for smartphones have over developing the same application as a web application?

Body:
Let's take the Facebook application as an example. Why did they develop an application when the users could just access to their page and do the same? For me that represents more maintenance and more cost because for each feature added to the web application that feature will have to be added to the smartphone application as well.

So why would I want to develop more than once (for each patform iOS, Android, etc) when I could just have one web application? What benefits do I get? The only one that comes to my mind is GPS feature.

EDIT:

My question is more oriented towards business applications that are going to be used only by some members of the company, it's not about selling the application (private use). So contrary to what some answers say about that by developing as a smartphone application it will benefit from more sells because of the "smartphone stores" for me this point is not important because the application is for private use.

By developing the application as a web application it means that it can be accessed through smartphone browser and also in a PC (any capable browser), but developing as a native application would limit this to only some kind of smartphone so we would be limiting  the use.  On the other hand developing it as a web application means that in order to access the application an Internet connection must be available.

So keeping this in mind how would you convince your boss to write the application for a given smartphone platform (iOS/Android) vs developing it as a web application?


答:
There are several advantages of creating a native app:

Better control over the UI experience - the mobile web developer would either need to recreate or use frameworks that emulate native UI artifacts

Access to platform APIs that might not be available to web apps - this is currently the biggest advantage for native apps

Potentially lower network usage at runtime - the native app would only need to access the network for data, while the web app might need to completely load at run-time.

As you've noted, developers native apps do have the disadvantage of building and maintaining apps for multiple platforms. This factor might not be a significant disadvantage if the developer is focused on only one platform.

Some discussions in blogs that you might be interested in reading:

Apps vs the Web by Matt Gemmell

Native vs Web Apps from MobiThinking


答:
I read an argument against debugger debugging here recently (or was it StackOverflow?). You should have test cases against your code. If your tests pass, your debugging probably isn't going to exercise the bug (assumption: you will debug with data similar to your test data).

On the other hand, logging is mandatory. If you pass your tests and deploy to production, you may find that you have a bug. The evidence of the bug is from something that happened in the past. i.e. someone says, "How did that get in there?" If you don't have good logs, you'll never find the cause. Even a debugger may be of no use at that point because you don't know what the data looked like that actually exercised the bug. You need to be able to debug the application from the logs.

Unfortunately, I'm paraphrasing quite a bit, and may be doing the original argument a disservice. In particular, the position of "There are important debugging aides to spend development time supporting" might be orthogonal to the importance of debuggers. But the part about the difficulty in setting system state in a configuration that makes debugging useful for finding bugs struck me as something to think about.


问:
Semantic or structure - which should get preference for variable naming?
We've a call stack in our project. The program is written for microcontroller, the language is C. The call stack is basically an array of integers. The variable that represents this call stack ends with the string _stack.

I was reviewing the implementation. The feature is reset recovery, not the call stack, but the call stack is part of the feature. When I first saw the variable, I thought it is used as a stack. So I assumed the following:

No entries other than the last entry can be accessed.

There will be PUSH/POP/CLEAR/TOP operations.

Next, I found that the first entry (index 0) is always checked in a special condition. I also found a function where all elements of the array are read sequentially from index 0 to top. Both of them are invalid stack operation.

I am thinking that the variable name should not contain the string stack as it is not a stack, rather it is used as a list. But the coder is showing valid logic, that according to semantic meaning, it's a stack and there is in fact PUSH operations.

Should the variable be named with *stack*?

答:
SHUZAN held up his staff and waved it before his monks.

"If you call this a staff," he said, "you deny its eternal life. If
  you do not call this a staff, you deny its present fact. Tell me just
  what do you propose to call it?"

If it's a variation or embellishment of a stack, I'd be fine with calling it a stack.

But I do hope that there is a bit of commentary or documentation that explains what information it represents, what the normal stack-like operations mean, and why it's necessary to have the others that don't follow the stack discipline.


答:
Personally, I try to minimize the use of a debugger by:

using static checkers and similar compiler options which hint at possible sources of bugs just by analyzing the code

writing code with as few side effects as possible, in the most functional style possible, eliminating mutable state where possible

writing unit tests with the minimal reasonable granularity

not swallowing exceptions

Of course, everyone makes errors, so even when composing programs this way, if a test fails, I use the debugger to inspect a value of an intermediate expression. But by adhering to the above principles, the defect is easier to locate, and debugging doesn't mean a painful, indeterministic process.


答:
Probably the most important reason is mind share.  What almost every internet company wants is for your mind to be tuned in to their product.  And one way to build mind share is to make access to the content as easy as possible.  How do the two delivery mechanisms compare?

Mobile Web Application:

User Thinks "I want to go to Facebook"

User clicks on "Internet"

User clicks address bar

User types "facebook.com"

Native App:

User looks at applications installed, and sees Facebook!

User clicks Facebook!

Not only is it easier for a user to use an application, but every time they look at their applications they will see Facebook just one click away.  They don't even have to think "I want to go to Facebook".

That is how you build mind share.


答:
Two  main reasons.

You can scoop up some money from the AppStore, many apps out there could easily have been developed as plain WebSites but its harder to make money that way. Even a free app can generate income from advertising.

You can put an "In Your Face" icon on the users "home" screen. So much better than a web page bookmark hidden three or four finger pokes from the user's home screen.

Technically the only reason for preferring an App to a Web Page is if you require a reasonable amount of data to be stored locally on the device, or, the app can actually function stand-alone without a network connection.


问:
C++ Renaissance - marketing slogan?

Possible Duplicate:

  What does the latest “C++ Renaissance” mean?

Lately, I hear a lot about C++ Renaissance. What is that?

C++ is currently undergoing a renaissance. This means that, by definition, the language, compilers and compositional tooling are evolving and coalescing into a state that maximizes native developer efficiency, productivity, and creativity across hardware and software domains.

I agree that C++ needs a lot of improvements, mainly, because it was updated in Neolithic Age (98,03).
What really bugs me is the Build conf. They've showed a few metro style apps written in C++ and XAML - like RSS reader or Piano.

I have a feeling that C++ is an overkill for this kind of apps and only case when I see the advantage is battery power, but is it true? C# as well as C++ calls WinRT which is native and C# has only tiny runtime overhead.

Can someone provide case study or hard data where use C++ in windows 8?

I think it will be status quo (games, servers, OSes, databases, apps like Photoshop will be C++ and other client apps run .Net) and renaissance is just a marketing slogan.

答:
C++ is starting to see some more importance on server side applications. Efficiently using the processor saves millions in server costs. If your app runs 7 times slower then you need to buy 7 times the servers, 7 times the cooling costs, 7 times the floor space, etc. Facebook started using some C++ for this reason. Google uses many languages, but their core is C++. If you expect massive load, your life can be made much easier if you use a native implementation from the start.

People seem to think garbage collection is what makes development easier. In my experience it's not, especially when your code is holding external resources.  The C++ model of destructor clean up is cleaner and more modern than the Java model.

Consider this java psuedo code:

```<code>public void someMethod()
{
        FileObj f = null;
        try
        {
          f = new File("/somePath/myFile.txt");
          String str = f.read();
          System.out.println(str);
        }
        catch(CustomException ce) { /*la */ throw ce; }
        catch(PathNotFoundException pe) { /*la */ throw pe; }
        catch(Exception e) { /*la */ throw e; }
        finally
        {
            try { if(f !=null) f.close(); }
            catch(Exception e) { /*la */ throw e; }
        }
}
</code>```

In C++ you could so something just as safe, without so much bloat. Just one line of code with all the saftey of the pseudo code above.

```<code>void someFunction()
{
   FileObj f("/somePath/myFile.txt");
   string str = f.read();
   cout << str;
   //the file is magically closed even if an exception occurs during f.read();
}
</code>```

Edit: Changing pusedo-code methods from "main" to "someMethod".

Edit: Re-throwing exception in java pseudo code to make it equivalent to the C++.

Edit: Re-naming File to FileObj so psuedo code is not confused with real java libraries.

OwnerDisplayName: lukas

Title: C++ Renaissance - marketing slogan?

Body:
C++ is starting to see some more importance on server side applications. Efficiently using the processor saves millions in server costs. If your app runs 7 times slower then you need to buy 7 times the servers, 7 times the cooling costs, 7 times the floor space, etc. Facebook started using some C++ for this reason. Google uses many languages, but their core is C++. If you expect massive load, your life can be made much easier if you use a native implementation from the start.

People seem to think garbage collection is what makes development easier. In my experience it's not, especially when your code is holding external resources.  The C++ model of destructor clean up is cleaner and more modern than the Java model.

Consider this java psuedo code:

public void someMethod()
{
        FileObj f = null;
        try
        {
          f = new File("/somePath/myFile.txt");
          String str = f.read();
          System.out.println(str);
        }
        catch(CustomException ce) { /*la */ throw ce; }
        catch(PathNotFoundException pe) { /*la */ throw pe; }
        catch(Exception e) { /*la */ throw e; }
        finally
        {
            try { if(f !=null) f.close(); }
            catch(Exception e) { /*la */ throw e; }
        }
}

In C++ you could so something just as safe, without so much bloat. Just one line of code with all the saftey of the pseudo code above.

void someFunction()
{
   FileObj f("/somePath/myFile.txt");
   string str = f.read();
   cout << str;
   //the file is magically closed even if an exception occurs during f.read();
}

Edit: Changing pusedo-code methods from "main" to "someMethod".

Edit: Re-throwing exception in java pseudo code to make it equivalent to the C++.

Edit: Re-naming File to FileObj so psuedo code is not confused with real java libraries.


问:
Are enforced Professional Development Plans useful?
Many companies, especially larger ones have mandatory professional development plans for their employees. Employees and managers set out a personalized professional development plan and follow up on the progress every so often.

As a developer, do you find such PDPs useful, do you follow through with your commitments?

As a manager, do you think such PDPs bring value to the company and improve the overall quality of the employees?

It seems that good developers will continue to educate themselves and strive to be better regardless of companies' procedures while bad ones won't.

Are there benefits of having PDPs or is it just something managers feel they need to do?

答: Frankly, I was hired to do technical stuff (writing code is only part of my job, though the other aspects are also technical) and I have virtually no tolerance for red tape.  I tend not to even look at most of it until I've been nagged about it more than once, especially if the person asking for it is just an administrative person and not my boss.  I suspect a PDP would be yet another one of these things and I would grudgingly do it while waiting for code to compile or run, just to get rid of whoever was nagging me about it.</p>


答:
Downloading on a mobile device consumes battery power.  A web app has to download both presentation code (HTML5,CSS,JavaScript,etc.) as well as the content that the user wants to see.  A native app only needs to down the user's desired content, thus being faster and more conservative of the users data allotment and battery life.

A native app may also require less layers of interpretive software, and use the native UI controls more directly, thus providing a more responsive user experience.  New UI features are often added directly to the native OS before they are made available (if ever) to the web browser.

Native apps have been reviewed by Apple, and are thus regarded as safer than web site URLs by some users. Many users are also used to discovering apps and spending money shopping in the devices App store.
Thus, many users are biased towards native apps, possibly for the above reasons in general, even if none apply to your particular web site.


问:
Managing lots of little (sometimes contradictory) changes
I work in a large company and most coding projects are fairly structured with a project plan and review process.

However, for existing support there are occasional periods where a department will need lots of tiny changes made to an existing app or site such the accounting department at the end of a fiscal year.

The problem is that they get incredibly busy and my team gets a slew of tiny emergency changes thrown at us.  We need to be flexible enough to support their needs as they are real and provide a great deal of value to the company.  On the other hand, given how crazy their environment is, they sometimes give us contradictory changes (change the text to 10pt, then the next day change it to 12pt).

Again, the changes are trivially tiny but they can suck up a developer's day given how frequent they are.  I'd like to push back and set some fair limits for how we'll handle these requests going forward.  Is there a best practice for handling these types of small changes?  The department in question is far to busy to commit a lot more time to working with us.  We also don't charge back so it's hard to communicate the problem to them.  What's a good approach to resolving this?

答:
One thing you should definitely consider is that they too may be reacting to lots of time critical requests. Taking your example of "change the text to 10pt, then the next day change it to 12pt", unless you have reason to believe that they are deliberately screwing with you, which it does not seem like they are doing, then think about why are they asking for these changes? Is it because someone is asking them for these changes?

Perhaps the outside auditors are placing demands on the accounting department at year end? Perhaps they have to comply with changing outside reporting requirements?

My suggestion would be to meet them when they are not busy (and definitely not at year end) to understand what they are going through. If they, like you, are feeling pressure at year end then perhaps the best solution is to develop a joint staffing plan where you schedule someone from your department to be available to meet these "emergency" requests and they assign someone from their department to act as the liaison to work with your person. If in fact the work being done is of high value to your company, then you can gender a lot of good will by helping them in this way.


答:
Depends on the scope of a problem.  If the program is small and things are well-divided you probably can figure it out by looking.  If the program is 4.5 million lines of code developed by a team of 100+ people over the course of several years then certain bugs will be impossible to spot.

The one in question in said program (in C) was a memory overwrite.  The debugger with a memory breakpoint identified the offending line of code as soon as the bug appeared.  But in this case there is no way someone could have read and retained all 4.5 million lines of code to identify the one spot someone wrote past their array (plus they'd have to have known the runtime layout of the memory for the gargantuan program's state about 10 minutes into a long run of inputs to get it to that point).

Point being: In small programs or things that are highly modularized you can get away w/o a debugger.  If the program is really big and complex then the debugger can save you lots of time.  As others have said, it's a tool, and it has its situations where it excels above any other method, and others where it isn't the best choice.


问:
How to make code writing more accurate?
I am trying to practice writing code for a long period of time before compiling and write unit test (if possible) for what I wrote (the language is C++). Of course, I got the IDE support (Emacs or Eclipse for on the fly error detection and code completion) with minimal or no error. I practice this ability because the pattern "trial and error" in which a bit of code is written and then build/run to check the correctness is not productive as I feel.

However, isn't what I am doing counter the purpose of testing? Maybe, the point of my practice is not to assure 100% logic correctness, but rather, 100% or close to 100% syntax correctness, in order to vastly improve productivity. I will try to practice with the small piece of code first, and then improve gradually as time passes.

What's your opinion on code writing and productivity in general? Do you practice like I do or do you have much better method? (Aside from being in the "flow", or extremely concentration). I concern this matter because I heard that some people are an actual human compiler, and it seems like they can directly translate the logic to code as their natural language.

Edit: I was a bit wrong when I mentioned not to improve logical correctness. Yes, logical correctness counts as well. What I want is to practice programming to the point where I can keep writing code for a long period of time with minimal mistakes (such as I can write 1000 lines of code,a and only a few trivial errors occur).In case of C++ or any language, using external libraries require you to understand many dependencies of the libraries to use it correctly in your code. For example, if you use Spring framework in Java, you have to make sure the xml, the server etc... are set up correctly. I consider this is also a form of syntax, and one way to achieve "syntax correctness" is to practice it frequently to the point when you can minimize the most mistakes written by hands. This is similar to when we first start learning programming, sometimes/often we miss the semicolon. Then we learn the mistake and improve it.

答:
Like all things in life, you should be trying to find a balance that works for you. You want to maximize your productive time by trimming away wasteful practices, which is good Lean thinking, however this needs to be done without incurring a wasteful cost elsewhere, and it's here I see the greatest risk when you state your desire to code for long periods of time without compiling.

Think about what you are doing when you write software.  You spend time thinking, and typing, and correcting, and testing, debugging, and so on. Chances are that you probably spend less time simply typing in code that will work first time, unless you are a serious genius or perhaps a little OCD as you type.

So how do you test your code?  Do you write tests first, or do you do all of your testing at the end? Both options will have a serious impact on the time it takes to successfully implement your code. Many of us who have been practicing Agile for years now have found that writing tests before writing code results in an overall efficiency increase.  This is because the testing is done, out of the way, and you only write enough code to make the tests pass.  It's lean, and while the up front development time is greater, the debug and test time is usually completed in a shorter time.

Yet regardless of whether you test first or test last, if there is one thing that I have learned the hard way over the years, its that your greatest coding failures usually occur after your largest coding changes. Think about this for a moment.  You are writing code, and you're in the zone so you just keep writing it.  Suddenly you realize that something else needs to be changed ever so slightly in order to accommodate your code. You look at it carefully, make your changes, and continue coding.  When you compile your code you suddenly find an error or two.  After fixing the error, the code compiles for the second time, and when you execute your code, it works almost as you wanted it two, but there is a bug. Fix the bug, and recompile, then there is another bug... and so on. I'm describing this as an issue isolated to a single developer, but what happens when you are working on the same source files, and you need to deal with branches, merges etc...?

What I am trying to say, is that getting code compiling is the smallest part of a much broader exercise.  Time spent up front refining your tests and executing them often against code is very efficient, because it saves you valuable time later on, particularly when your job involves working with other software developers. The real benefit however comes when working with a good unit testing framework, because you will be able to get instant feedback so that not only will you know if your code compiles, but you will also know instantly if your code actually works. This in itself is a huge time saver, because it can keep you from obsessing over the state of your code, freeing your attention up for other things.

Title: How to make code writing more accurate?


问:
What is the point of the string.Empty property
Why was the property string foo = string.Empty included in the BCL? It seems more verbose and no clearer than just using an empty string (string foo = "")

答:
It is a matter of optimization of memory consumption and an optimization of string comparison. Every time you're using an empty string in your application, you are allocating a string object containing 0 characters. As for string comparison it can be done by comparing references (pointers) instead of character by character, which is a faster even for empty strings.

If you are using many times the same string in your application you can use the same kind of mechanism by calling String.Intern() with your string. But if you are using each string only once, then you'll only use more memory.

So String.Empty is only a special case optimization which is worth to do for most .Net applications, that's why it was integrated in the BCL.

For more detail on this subject I strongly recommend reading Eric Lippert's blog post.

You should also take a look at this documentation referenced by his blog post.


问:
GIT branch model for derivative work
I'm planning on using Vincent Driessen's branching model which I found great for my current development. I think Vincent approach is very general to any development project but I'm finding it difficult to handle the following scenario.

I'm working on an application that will be branded to several customers, so each one of my bundles is a different branch that I rebase from develop branch each time a new build is going to be released. Each brand has its assets (images and text) and they do not conflict with changes in develop branch because in that branch I never touch the assets.

My question is, now that I'm planning on using it, how can I handle different versions based on the same code base but with different assets?

答:
If each brand has independent assets then you can create each customer branch from develop and then pull future changes in as required. Individual assets can be created, edited and committed on the appropriate customer branch.

A nice side-effect of this is that you could have common assets on develop if that makes sense.

Depending on how distributed your development is, you might consider pulling from master rather than rebaseing. You don't want to rebase if commits are being pushed around to other repositories.

To summarise: code changes on develop; asset changes on customer-X; occasionally pull from develop to customer-X. Sorted.

Title: GIT branch model for derivative work


问:
Functional Programming approach for a simplified game using Scala and LWJGL
I, a Java imperative programmer, would like to understand how to generate a simple version of Space Invaders based on Functional Programming design principles (in particular Referential Transparency). However, each time I try to think of a design, I get lost in the morass of extreme mutability, the same mutability which is shunned by the functional programming purists.

As an attempt to learn Functional Programming, I decided to attempt to create a very simple 2D interactive game, Space Invader (note the lack of plural), in Scala using the LWJGL. Here are the requirements for the basic game:

User ship at the bottom of the screen moved left and right by the "A" and "D" keys respectively

User ship bullet fired straight up activated by the space bar with a minimum pause between shots to be .5 seconds

Alien ship bullet fired straight down activated by a random time of .5 to 1.5 seconds between shots

Things intentionally left out from the original game are WxH aliens, degradable defense barriers x3, high speed saucer ship at at the top of the screen.

Okay, now to the actual problem domain. For me, all the deterministic parts are obvious. It's the non-deterministic parts that seem to be blocking my ability to consider how to approach. The deterministic parts are the bullet's trajectory once they exist, the continuous motion of the alien and the explosion due to a hit on either (or both) of the player's ship or the alien. The non-deterministic parts (to me) are handling the stream of user input, handling fetching a random value for determining alien bullet firings and handling the output (both graphics and sound).

I can do (and have done) lots of this type of game development over the years. However, all of it was from the imperative paradigm. And LWJGL even provides a very simple Java version of Space invaders (of which I began moving to Scala using Scala as Java-without-semicolons).

Here are some links that talk around this area of which none seem to have directly dealt with the ideas in a way a person coming from Java/Imperative programming would understand:

Purely Functional Retrogames, Part 1 by James Hague

Similar Stack Overflow post

Clojure/Lisp Games

Haskell Games on Stack Overflow

Yampa's (in Haskell) Functional Reactive Programming

It appears that there are some ideas in the Clojure/Lisp and Haskell games (with source). Unfortunately, I am not able to read/interpret the code into mental models that make any sense to my simpleminded Java imperative brain.

I'm so excited by the possibilities offered by FP, I can just taste the multi-threaded scalability capabilities. I feel like if were able to grok how something as simple as the time + event + randomness model for Space Invader can be implemented, segregating the deterministic and non-deterministic parts in a properly designed system without it turning into what feels like advanced mathematical theory; i.e. Yampa, I'd be set. If learning the level of theory Yampa seems to require to successfully generate simple games is necessary, then the overhead of acquiring all the necessary training and conceptual framework will vastly outweigh my understanding of the benefits of FP (at least for this over-simplified learning experiment).

Any feedback, proposed models, suggested methods of approaching the problem domain (more specific than the generalities covered by James Hague) would be greatly appreciated.

答:
The non-deterministic parts (to me) are handling the stream of user input ... handling the output (both graphics and sound).

Yes, IO is non-deterministic and "all about" side-effects. That is not a problem in a non-pure functional language such as Scala.

handling fetching a random value for determining alien bullet firings

You can treat the output of a pseudorandom number generator as an infinite sequence (Seq in Scala).

...

Where, in particular, do you see the need for mutability? If I may anticipate, you might think of your sprites as having a position in space that varies over time. You may find it useful to think about "zippers" in such a context: http://scienceblogs.com/goodmath/2010/01/zippers_making_functional_upda.php


问:
What are the reasons one would use fully qualified class names in source code?
I recently ran across code where the developers used both fully qualified class names AND imported class names in their source code.

Example:

```<code>import packageA.Foo;

public class Example {
    public packageB.Bar doSomething() {
        final Foo foo = new Foo();
        ...
    }
}
</code>```

I was under the impression that the only reason one might want to use fully qualified name for classes in source code is when they have identical class names in two different packages and they need the fully qualified name to distinguish between the two. Am I wrong?

答:
No - you are quite right. Using fully qualified package names is usually considered poor style, except when it is necessary to avoid collisions.

If a package name is especially short and descriptive, using qualified identifiers can make code more expressive. But the JLS prescribes domain-based names for most packages, so package names usually aren't short and descriptive.


问:
async & await - poll for alternatives
Now that we know what is in store for c#5, there is apparently still an opening for us to influence the choice of the two new keywords for 'Asynchrony' that were announced by Anders Heijsberg yesterday at PDC10.

```<code>async void ArchiveDocuments(List<Url> urls) {
    Task archive = null;
    for(int i = 0; i < urls.Count; ++i) {
        var document = await FetchAsync(urls[i]);
        if (archive != null)
            await archive;
        archive = ArchiveAsync(document);
    }
}
</code>```

Eric Lippert has an explanation of the choice of the current two keywords, and the way in which they have been misunderstood in usability studies. The comments have several other propositions.

Please - one suggestion per answer, duplicates will be nuked.

答: task (for method declaration) and async (within method body)

Title: async & await - poll for alternatives