答:
When I read your requirements, I immediately thought of using R, like @JimmyHoffa. In addition, I have done a great deal of programming in R (and Python). I think R is ideal for this kind of work because of:

The large amount of statistical tools readily available. Think of Princple Component Analysis (PCA), all kinds of optimization techniques, etc. And if it is not already available there are many, many more packages available on the Comprehensive R Archive Network (CRAN), there are more than 3000 packages there. A nice way to explore these packages theme wise (e.g. econometrics, spatial data analysis, etc) is to look at the different Task Views that are available here.

It is open source, and freely available.

A large and active community which you can use to get answers to specific questions. For example, the R-help mailing list, or the [r] tag on StackOverflow.

All the data structures you requested (floats, matrices, arrays, tables, etc).

A powerful, functionally oriented, syntax that suits the data oriented nature of data analysis well. Explicit for loops are rarely needed (although they exist in the language), instead you use apply style loops. This means that you apply a function over a datastructure. For example, you can apply the mean function over the rows of a matrix to get the row means:

```<code>apply(matrix, 2, mean) # where 2 is the dimension over which to apply
</code>```

this shares some similarities with list comprehensions in python.

Easy incorporation of C++, Fortran etc code for when you want to replace a performance critical section by compiled code.

Body:
When I read your requirements, I immediately thought of using R, like @JimmyHoffa. In addition, I have done a great deal of programming in R (and Python). I think R is ideal for this kind of work because of:

The large amount of statistical tools readily available. Think of Princple Component Analysis (PCA), all kinds of optimization techniques, etc. And if it is not already available there are many, many more packages available on the Comprehensive R Archive Network (CRAN), there are more than 3000 packages there. A nice way to explore these packages theme wise (e.g. econometrics, spatial data analysis, etc) is to look at the different Task Views that are available here.

It is open source, and freely available.

A large and active community which you can use to get answers to specific questions. For example, the R-help mailing list, or the [r] tag on StackOverflow.

All the data structures you requested (floats, matrices, arrays, tables, etc).

A powerful, functionally oriented, syntax that suits the data oriented nature of data analysis well. Explicit for loops are rarely needed (although they exist in the language), instead you use apply style loops. This means that you apply a function over a datastructure. For example, you can apply the mean function over the rows of a matrix to get the row means:

apply(matrix, 2, mean) # where 2 is the dimension over which to apply

this shares some similarities with list comprehensions in python.

Easy incorporation of C++, Fortran etc code for when you want to replace a performance critical section by compiled code.


问:
Better php framework for shared hosting
I need to develop an app for booking appointments. This is going to be hosted in a shared server. So performance is the most important thing. I have used symfony2. I quite liked the framework. But seems to be heavy.

Which framework would suit me considering my requirements? I have shortlisted three frameworks yii, symfony2 and ZF2. I am not asking which framework is better.

All the three are good frameworks. I want to know which will suit my requirements. My first priority would be performance (I will be using AJAX wherever possible), second would be maintenance and development time and third community support. Or should I use my own handlers to separate views and logic and just use raw php?

答: @tim's answers is the best one I think but if you still need to pick a PHP framework, then consider Codeigniter too. It works very well on a shared server, no command line access needed, very good performance and a large active community</p>

ContentLicense: CC BY-SA 3.0

Title: Better php framework for shared hosting


问:
How to plan a client/server app networking architecture to cope with multiple unrelated exchanges of data?
I'm coding a server/client application pair in Java, as I learn about it. I have basic functionality of sending a message to the server and parsing it but in thinking about the big picture of their communication, I'm stumped about where to go from here.

Both the client and the server have to be able to initiate an exchange of data so I need to have one thread reading at each side, at all times. On top of that, when one initiates an exchange, it needs to listen for the reply. If I do that, though, I'd have two threads reading data, which I guess wouldn't end well since, from my understanding, I wouldn't be able to make sure the data gets read in the thread I want.

I see a few options but I'm not confident at going too far with each solution since my knowledge doesn't let me think too far ahead.

Use only the first thread that was originally waiting for data before the exchange, to also read the reply for the query that was just sent by a different thread, and forward the data where it belongs.

This sounds difficult. If I read the data in the same thread that requested it, it would be very straightforward compared to this.

Start reading the InputStream in the same thread that requested data and make the thread that was originally listening, wait.

My problem with this is that, if there's other data arriving by the same client that is unrelated with the query that was just made, it would be fetched by this thread instead of the other one, which kinda defeats the purpose of reading the data here.

Establish another connection from the client, to another port, after the first is established. Then I could use one socket for exchanges initiated by the other side, and the other to listen for replies of queries made in the meantime.

This way I'd know exactly what is going where, but wouldn't I have this same problem further down the road if I have two queries waiting for data at the same time?

This sounds like simple functionality, trivial to find in many applications, so I'm guessing there's some tried and true method out there and there's no reason for me to try and reinvent the wheel here.

So, to sum it up, what's the recommended way to set up client/server applications that can cope with possibly overlapping dialogs, initiated by either one, at unpredictable times?

I started to modify some parts of the question to make it a bit clearer but I ended up almost rewriting it completely. If it's still a bit confusing is because I am confused. I think I'm missing some simple point but I haven't been able to find examples that show this.

答:
Using multiple connections per user could be problematic because you will hit the servers connection limit earlier when you have a lot of users.

TCP, however, has the advantage that packets are always received in whole and in order. You can use that to implement your own application-level session handling system which works in a preemtive ("time-sharing") multi-threading way.

When there are multiple file downloads taking place at the same time, you could split each file transfer into individual packets and prefix each packet with an identifier which says to which file transfer it belongs. Then you put the packets of each transfer into a queue and process these queues in round-robin order. That means when you have 3 file transfers A, B and C consisting of 3, 5 and 7 packets each, you would send these 15 packages in the order ABCABCABCBCBCCC. Make sure that you are able to add a new queue at any time between sends so that you can enter a new transfer while other transfers are running.

On the other side you read the prefix of each packet to find out to which file transfer it belongs and append it to the corresponding input stream.

A good API to manage all this on Java is non-blocking IO. You should use that anyway on a server which handles a lot of users, because that way you avoid to create individual threads for all users.

OwnerDisplayName: Smig


问:
Working with clients who don't know what they want
I have recently started a job that has me working on an existing system. It requires tweaks and updates as well as new code. I have done several maintainance/feature adding projects now, and several of them have ended up being significantly different from what was actually requested. So, I had to program the item several times to get it to where the requester wanted.

Now, I don't mind reprogramming the feature if that's what needs to be done. However, I would like to decrease turnaround time on my projects. The bottleneck seems to be in the requester's perception of what needs to be done. Do you have any ideas on what I could do to figure out what the requester needs more quickly?

答:
Lots, and lots of similar stories can be found here. I have never, even working as a subcontractor for another development company, found a client that knew exactly what they wanted.

I'm happy enough to work with someone who has a really good idea of what they DON'T want, or want to avoid. I can usually work from there to something that they are happy with.

My experience is mostly in application / platform development, though. Thankfully, I rarely have to deal with issues of aesthetics like web designers do.

ContentLicense: CC BY-SA 2.5


问:
script engine with no global environment (java)
I am curious about how global variables are handled by script engines. I am looking for a script engine that does not preserve the state of global variables upon invocation. Are there such engines out there? We are looking for a scripting language we can use under the script engine API for Java.

When making multiple invocations of a script engine, top-level calls to eval() or evaluate() method preserves the state of global variables, meaning that consequent calls to eval() will use the global variables as they were left by the last invocation. Is there a script engine that does not preserve the state, or provides the ability to reset the state, so that global variables are at their initial state every time the script engine is invoked?

答:
Any API to a scripting engine that allows for creation / teardown of the virtual machine associated with engine provides what you're looking for. Script hosts built for embedding into other software do this job well.

Lua is an embeddable scripting host, and this is what @delnan is talking about -- the API allows for the arbitrary instantiation of virtual machines that each have their own global state.

There are ways to do this in other scripting hosts (or rather, virtual machines). A .Net Common Language Runtime (CLR) can be invoked and used in a localized way via Microsoft's COM interface.


问:
Can I license a program under Apache License 2.0, if it is using/including Eclipse Link (EPL or EDL)?
Can I license a program under Apache License 2.0, if it is using/including EclipseLink?
(EclipseLink under Eclipse Public License or Eclipse Distribution License)

I did not change anything in EclipseLink.
I would realy like to distribute a Version that includes the needed EclipseLink jars, so that it is working "out of the box".

答: I had the same problem at some point and what I do is to distribute the build configuration i.e. the Maven pom.xml. This way you distribute the source to something that will pull Eclipselink but not package or hardwire it within. Then the users are then bound to both licenses. In my case the users are also free to stay at Hibernate or simply JPA.</p>

OwnerDisplayName: scherlock


答:
A few points of advice:

Listen to problems, Not Solutions. A lot of clients like to tell you how to solve their problems. Don't listen to them. You're the programmer, and it is your job to find solutions to problems. Instead listen to what problems clients are having, and figure out the best way to solve it. As others have said, clients don't really know what they want; sometimes you have to show it to them first.

Ask Questions. When you are done asking questions, ask some more. Clients are rarely forthcoming with details, as they don't really think about it. The only way you are going to get the information you need is to pry it out of them.

Get Things in Writing. Depending on the situation with the client, this can be really important later when they start complaining about how what you delivered "isn't what they asked for". And if nothing else, writing out detailed specifications can help you make sure you have all of the information you need, and help clear up ambiguities between you and the client.

Communication is key. Don't just talk to the client, get info, knock out some code and not talk to them until it's done. Always keep in touch with the client. Ask questions throughout the process. Show them the progress you've made and get feedback. It'll make everyone's life easier in the long run.

Title: Working with clients who don't know what they want

Body:
I have recently started a job that has me working on an existing system. It requires tweaks and updates as well as new code. I have done several maintainance/feature adding projects now, and several of them have ended up being significantly different from what was actually requested. So, I had to program the item several times to get it to where the requester wanted.

Now, I don't mind reprogramming the feature if that's what needs to be done. However, I would like to decrease turnaround time on my projects. The bottleneck seems to be in the requester's perception of what needs to be done. Do you have any ideas on what I could do to figure out what the requester needs more quickly?

ContentLicense: CC BY-SA 4.0


问:
SICP - Why use accumulate with cons when filter already passes back a list
In SICP 2nd Edition section 2.2.3,
the authors have the following code:

```<code>(define (even-fibs n)
  (accumulate cons
              nil
              (filter even?
                      (map fib
                           (enumerate-interval 0 n)))))
</code>```

My question is why did they use accumulate in this case? Couldn't they have got the same answer from  filter  without using accumulate?

答:
In that section of the book, filter, map, and enumerate-interval are presumed to return sequences, which are conceptually distinct from lists. You can implement sequences using streams, for example, though you can implement sequences using lists too.

So, in this case, the accumulate with cons is to convert the sequence to a list.


问:
How to take a step back and look at code with fresh eyes?
I've spent the last year as a one-man team developing a rich-client application (35,000+ LoC, for what it's worth). It's currently stable and in production. However, I know that my skills were rusty at the beginning of the project, so without a doubt there are major issues in the code. At this point, most of the issues are in architecture, structure, and interactions -- the easy problems, even architecture/design problems, have already been weeded out.

Unfortunately, I've spent so much time with this project that I'm having a hard time thinking outside of it -- approaching it from a new perspective to see the flaws deeply buried or inherent in the design.

How do I step outside my head and outside my code so I can get a fresh look and make it better?

答:
I know this situation very well. When I get stuck that way I try to take different points of view on the project.

1.) User / customer point of view - use feedback

Unfortunately we are caught in our code in a way that we aren't able to see our own flaws because we use our applications the way we have coded them.
Look at how people use it and try to figure out what the most intuitive user guidance would be.
Play around with UI prototypes.
This seems to be fun, but if you find out that you would be forced to recode huge parts of your code just by changing the usage logic than it's time to start a redesign cycle.

2.) Do a functional analysis of your code and visualize it

Some IDEs and frameworks push you to e.g. mixing UI and backend code. If you let this happen you will at some day face the situation that your code base can hardly be maintained because of nebulous  and hard to break dependencies. Especially mixing UI code with other code can lead to spaghetti code and redundant functionality.
Divide your code in functional blocks like e.g. database classes, communication classes, UI classes, core classes etc. and give the function blocks speaking names.
Then visualize the functionality with a graphical tool (I use a mind mapping tool) in order to find out whether your structure is logical and modular enough that you can reuse huge code blocks for different projects and you are able to replace them with newer versions without big pain.

The best way to do this in my experience is to create a document that visualizes all dependencies between your classes and their calls from your code. The result is a visualization of your interface design.
If this code map looks like a complete clusterf*** than it's time to act.
If not happened yet you should think about a suitable naming convention that represents your code structure in a way you don't have to think about how to call it and what it does.

3.) Use common approaches to quality assurance

My favorite is the FMEA. In terms of coding this means not only to analyze what went wrong in the past but also think about what could go wrong. A pretty common example is a suddenly dropped network connection. After you have done this you can classify the error conditions by consequences like data loss, crash, wrong calculation and judge the impact on the user.
If not done yet defining streamlined error and exception classes and routines can help you to keep your code clean and straight. The best way is to implement those in every new peace of code before even starting to write anything else. (Well, I'm guilty not always to follow this advice myself.)

In addition it helped me to generate and frequently update an "improvement proposal list" for my own code. (To be honest there's still a lot of code in my projects I'm definitely not proud of.)
I also try to take the time to collect and have a look at best practice code from API documentations, developer conferences or developer magazines.

Until this point there's no need to touch your code. It's simply about getting aware what's going wrong and finding a way to define how to improve your code.

Finally some tips for daily work from an old fart. Try to avoid to bite more than you can eat.
This leads to too much pressure for clean coding. You rarely get the time to do it right, but you will have to take the time to fix the flaws afterwards.

Nothing is as long-lasting as the provisional solution, but when it breaks it's often to late to fix it in time. Examples are nasty hacks or strange exceptions I used to get something to work despite e.g. a flaw in the underlying framework or OS. And then the flaw get's fixed or the new version simply drops the API…

If you are stuck and get forced to find a workaround than make comments and take notes which should be reviewed from time to time.
Normally we get better and better because of learning something new.
If you find a better way implement it as fast as you can.
Otherwise you might find yourself coding the workaround for the workaround and the exception of the exception one day.
(He who is without sin among you, let him throw the first byte at me.)


问:
Using database Indexes
This might sound like a naive question but when are database table indexes in mysql required? How do such indexes affect performance and why?</p>

答:
The purpose of database indexes is to increase the performance of searches in data tables.

As you might already know, for unsorted data structures, the asymptotic notation O(f(n)) for searches is O(n). Meaning that, in the worst case, all rows of the table are going to be looked in order to rows matching the WHERE clause (and the same goes for JOIN columns). It might not be that bad in a small table, but it can become really slow on a bigger table.

Since a data table cannot physically contain sorted data for multiple columns (generally speaking, it may only be physically sorted by a single column), indexes become handy. In summary, indexes are usually a B-tree (or a variant) sorted map containing a specific column data as key and the row information as the entry value. This way, the O(f(n)) can be reduced to O(log(n)).

Are indexes required? No. But your queries will show a huge performance boost, if you use indexes in the right way.

Yet the performance gain has its drawbacks: in order to increase the search performance, the insert and delete operations become slower (as the indexes must be updated). Here are some asymptotic amortized worst-case analysis for different data structures. Remember this is just an introduction on the matter. You should definitely take a deeper look on database indexes.

Title: Using database Indexes


答:
"Is this a smaller issue than I think it is, or is this a problem experienced by others as well?"

Sheesh.  Enough already.  If the code's in production, bug-free and doing what it's supposed to do, architecture is unimportant.  At least for now.

All of us hopefully learn as we go.  I've written a lot of code that I was proud of at the time I wrote it, only to decide it was awful a year or two later.  Right now I'm working on a multiyear project that's filled with incredibly crufty code, but the code works.  I'm taking a very conservative approach to touching any of it.

And so should you.  If you don't see any major architectural issues right now, after a year of work, I think it may be safe for you to assume, for now, that there are no important ones.  This isn't bad craftsmanship.  It's moving forward.

Title: How to take a step back and look at code with fresh eyes?

Body:
I've spent the last year as a one-man team developing a rich-client application (35,000+ LoC, for what it's worth). It's currently stable and in production. However, I know that my skills were rusty at the beginning of the project, so without a doubt there are major issues in the code. At this point, most of the issues are in architecture, structure, and interactions -- the easy problems, even architecture/design problems, have already been weeded out.

Unfortunately, I've spent so much time with this project that I'm having a hard time thinking outside of it -- approaching it from a new perspective to see the flaws deeply buried or inherent in the design.

How do I step outside my head and outside my code so I can get a fresh look and make it better?


答:
Basically, an index on a column allows you to very quickly find all rows of a table that have a specific value (or range of values) in that column, without having to look at every single row, and no matter how large the table is.

Thus, the index can drastically speed up queries which have a WHERE clause referring to that column, as well as JOINs and nested SELECTs. Especially for very large tables, indexes are absolutely essential to get good performance. But of course, they only help if you have them on the columns your queries actually use.

Title: Using database Indexes

Body: This might sound like a naive question but when are database table indexes in mysql required? How do such indexes affect performance and why?</p>


问:
Migrating from one PHP framework to another
I'm working with a web company that's approaching a point where it will likely need re-think the product as a V2 - due to outgrowing some of its V1 foundations and principles that have been built into virtually everything, from the data model to the user interfaces. For various reasons, this evolution might involve a migration from CakePHP (with which the V1 has been built) to Symfony or Zend.

I would like to ask for some experienced views on how people might have managed a transition like this for a website that has significant traffic and generates revenue. I don't want to open up a discussion on the pro's & con's of different PHP frameworks, or why this migration might be needed. Rather, I would be very interested in hearing whether there are some practical alternatives to essentially building a V2 from scratch alongside the V1 for a couple of months - and locking up precious coding time for the duration of this intense period. An example of such an alternative might be migrating an app in parts over a longer period of time.

I'd be grateful for any views from people who might have managed or been involved in such transitions.

Thanks in advance.

答:
Learn the new framework very well first, and make sure it is going to meet your needs, and that you really grok the paradigms of the new framework.  You are going to have to throw out a lot of code, and that's ok. The important thing is that you are using the new framework the way it was meant to be used, taking full advantage of it's features, and not being tied into ways of thinking from your old framework. Don't try to use Zend "the CakePHP way"*

For example, when I moved to using MVC framework from previous non-MVC ones, I didn't really get how models, views, and controllers were supposed to work, and I wrote some terrible looking code because I didn't understand the new way of doing things. You'd be better off sticking with an inferior old framework than having a poorly written app on a better framework.

*I'm not familiar with either, so I don't know how similar/comparable they are.


问:
Is there a way to display the stack during recursion method?
I'm trying to learn recursion.  I copied this bit of code from my book and added the displays to help me trace what the method is doing and when.

```<code>public static void main(String[] args) {

    System.out.println(sum(4));

}//main

public static int sum(int n) {
    int sum;
    System.out.println("n = " + n + "\n");
    if (n == 1)
        sum = 1;
    else
        sum = sum(n - 1) + n;
    System.out.println("n after function = " + n + "\n");
    System.out.println("sum after function = " + sum + "\n");
    return sum;
}
</code>```

Here's the results:

n = 4

n = 3

n = 2

n = 1

n after function = 1

sum after function = 1

n after function = 2

sum after function = 3

n after function = 3

sum after function = 6

n after function = 4

sum after function = 10

10

I'm getting hung up on what's being stored in the stack, or perhaps how it's being stored.

Is there a way to display what's in the stack while n is counting down to 1?

This is an odd concept - it's like an invisible loop storing values in a way I don't understand.

答:
You cannot access the stack contents directly from your Java code, but if you use a debugger (which is integrated in every modern IDE) you get something even better: it will list the stack of method calls and for each level, if you select it, the values of the local variables on the stack.

Here's a tutorial on how to use the debugger in eclipse.


答:
You can use a debugger like eclipse to view the stack at any given time, but trying to envision recursion as a loop isn't the best way to understand it.  As you go down the stack, you break off small pieces of the problem, until you get to the bottom of the stack, where the problem is trivial to solve.  Then as you go back up the stack, you put the pieces back together again.

```<code>sum(4)
sum(3) + 4
sum(2) + 3
sum(1) + 2
1
</code>```

sum(4) is broken down into sum(3) + 4.  sum(3) is broken down into sum(2) + 3.  Eventually you get to sum(1), which has a trivial answer of 1 (the first choice in your if statement).

There's no possible way to break it down further, so you go back up the stack, adding 2, 3, and 4.  It's a ride down and up the stack, a very different thing from a loop, even though they can accomplish the same calculation.

Title: Is there a way to display the stack during recursion method?

Body:
I'm trying to learn recursion.  I copied this bit of code from my book and added the displays to help me trace what the method is doing and when.

```<code>public static void main(String[] args) {

    System.out.println(sum(4));

}//main

public static int sum(int n) {
    int sum;
    System.out.println("n = " + n + "\n");
    if (n == 1)
        sum = 1;
    else
        sum = sum(n - 1) + n;
    System.out.println("n after function = " + n + "\n");
    System.out.println("sum after function = " + sum + "\n");
    return sum;
}
</code>```

Here's the results:

n = 4

n = 3

n = 2

n = 1

n after function = 1

sum after function = 1

n after function = 2

sum after function = 3

n after function = 3

sum after function = 6

n after function = 4

sum after function = 10

10

I'm getting hung up on what's being stored in the stack, or perhaps how it's being stored.

Is there a way to display what's in the stack while n is counting down to 1?

This is an odd concept - it's like an invisible loop storing values in a way I don't understand.

Body:
You can use a debugger like eclipse to view the stack at any given time, but trying to envision recursion as a loop isn't the best way to understand it.  As you go down the stack, you break off small pieces of the problem, until you get to the bottom of the stack, where the problem is trivial to solve.  Then as you go back up the stack, you put the pieces back together again.

sum(4)
sum(3) + 4
sum(2) + 3
sum(1) + 2
1

sum(4) is broken down into sum(3) + 4.  sum(3) is broken down into sum(2) + 3.  Eventually you get to sum(1), which has a trivial answer of 1 (the first choice in your if statement).

There's no possible way to break it down further, so you go back up the stack, adding 2, 3, and 4.  It's a ride down and up the stack, a very different thing from a loop, even though they can accomplish the same calculation.


问:
How important is it to learn makefiles?
I work in c++ mostly as a hobby (I'm still in school and therefor don't have a real job). The IDEs generate the makefile for me and so I'm wondering if it's worth learning how to make them myself. By "worth learning" I mean, should I drop everything and learn how to write them before continuing to learn c++? Is learning them going to be really necessary? If so, should I learn about them (general syntax and understanding how they work etc.) or really learn how to write them?</p>

答:
You should always try to understand the build system you are using.

That does not necessarily mean you have to be able to create all of the build files by hand.
The important part is understanding what the build system is doing for your project and the general ability to compile small projects manually (as in "typing commands on a terminal").

I just tend to think that creating (simple) Makefiles is the easiest step to understand what is going on, but you might have other means of understanding how to build things.

Why/when to learn Makefiles

If you keep programming for Windows only and don't expect anybody else to compile your code, feel free to compile the code how you like.

If you want to program compiler agnostic (as in "let others decide what compiler or IDE they want to use"), then you should learn another build system than just letting your IDE "deal with it".

If you want to program for different platforms, then you certainly need to use a widespread build system.

That still doesn't mean you have to know how the autogenerated Makefiles work in detail.
You just have to know how the input files for the build system work.
These just happen to have a similar syntax sometimes.

I personally really like Makefiles and use them for many things. Not just compiling code.
I create a Makefile for every bigger pdf I create (with LaTeX) and every project I need to automate a couple of tasks in (building, packaging, uploading, updating dependencies from source repositories, pull/push manual backups)

However, I am working on the terminal a lot and I am working with Linux.
I don't use what you would call an IDE other than vim (powerful text editor) and console tools.
This might be very different for you.

If you ever complained about having to run different re-occuring commands just to "update"/package/upload/.. a "project",
then learning how to write Makefiles might be something helpful for you.

If you have and use tools/GUIs/IDEs for everything,
then you might not get anything out of that knowledge.

Title: How important is it to learn makefiles?


答:
Learning how to write Makefiles is a good idea for a number of reasons.

Make is a language which lets you encode dependencies between components via rules. You will get a lot of experience with writing code this way, and it broadens your tools for thinking about solving programming problems.

The principles you learn with Make can be used with Ant, Maven, and Rake if you choose to learn programming in the Java or Ruby world.

Many IDEs have magic files which carry configuration information to help you build your software. If you don't believe me, try to write a script to build your software without the IDE. When you write your own Makefiles, you become very aware of the dependencies between your code, libraries, and your environment variables. As systems get larger, this turns out to be a useful tool for debugging your system.

Title: How important is it to learn makefiles?

Body: I work in c++ mostly as a hobby (I'm still in school and therefor don't have a real job). The IDEs generate the makefile for me and so I'm wondering if it's worth learning how to make them myself. By "worth learning" I mean, should I drop everything and learn how to write them before continuing to learn c++? Is learning them going to be really necessary? If so, should I learn about them (general syntax and understanding how they work etc.) or really learn how to write them?</p>


问:
Network computation
I'm pretty sure that someone has already thought about it and researched it extensively, but I'm having trouble finding any materials or even keywords to look for, for the idea that I was thinking about recently.

I thought about this concept, where in distributed systems, actual computation and processing would happen on the network, rather than on nodes (server or client) on their way from the source to the destination. Where network routers in addition to routing network packets to the next node until delivered to the destination, they would also execute some embedded instructions in those packets.

So for example a network packet would be split into two areas: data and instructions (+ some headers) And when a router routes a packet to the next router, it would send a transformed packet according to the embedded instructions:

```<code>+----------------------+
|Network Packet Headers|
+----------------------+
| DATA SLOT 1          |
| DATA SLOT 2          |
| ..........           |
| DATA SLOT N          |
+----------------------+
| Increment slot1      |
| SLOT3 = SLOT1 + SLOT2|
+----------------------+
| instruction ptr      |
+----------------------+
</code>```

So that by the time those network packets would get to their destination, a portion of it (depending on how many hoops it had to go through) would already be computed (say audio decoded, etc..) offloading both endpoints.

Routers are technically capable of doing this. They do process data based on network packet's values - like choosing where to send the packet next basing on the IP header. There is nothing stopping them from being utilized as "the real cloud", right? Each router would execute one packet or a couple of instructions from that packet (and update the instruction pointer) depending on it's HW resources and capabilities. So a network packet would be a stack frame rather than just a network packet.

Of course, there is a whole class of problems associated with this model, like properly partitioning data (or even the ability to do so.), but it's all based on old concepts from heterogeneous computing and functional programming.

Could someone please point me to any research, materials or projects that deal with similar concepts?

Thanks!

答:
Routers are very specialized and optimized to do just what they do very well.  Why would you want to burden them with extraneous tasks, and why would the providers of network infrastructure be interested in adding this to their burden?

I can't think of any general computational task that this kind of methodology would be useful for, but perhaps some kind of network specific task could be considered, for example some kind of "onion" routing, to help conceal the origin of network traffic, or conversely adding some tracking information about conditions along along the route.

Title: Network computation


问:
Visualization of N>2-D array?
I have an array of dimension 5. But, I can't figure out how to visualize that array?

```<code>int[][][][][] array = new int[4][4][4][6][2].
</code>```

Is there a good way to visualize arrays with dimension counts of 3 or more?

答: A 2d array of 3d cubes would visualize it, although there's no good general way to show all the data at once in any meaningful way.</p>

Title: Visualization of N>2-D array?


问:
Is it better to use $filehandler or FILEHANDLER?
It seems like FILEHANDLER is more commonly used as a handler naming convention than $filehandler.
But it can give a bareword error if one forgets to use *FILEHANDLER in some constructions.

What are advantages and disadvantages of HANDLERS and $handlers?

Which naming convention is a better practise, and why?

答:
It is better to use $filehandler because your filehandles will be lexically scoped. It means you won't accidentally sabotage or clash with another filehandle. You'll get a warning if you try to declare another variable with the same name. This format was introduced in Perl 5.6 so it is a newer format.

Bareword filehandles are global names. You could overwrite an existing filehandle with the same name without knowing it. It could cause some confusion if you have a constant or subroutine with the same name. And you probably won't get any warnings if you do have any of these clashes.

btw, this is one of the items listed in Perl Best Practices by Damian Conway. It's also better to use the 3-arg form of open: open my $fh, '<', $file.


答:
Think of each level of multi-D array access as an address with meaning that leads to something specific.

```<code>x[0][1][7];
</code>```

This could represent whatever's at the space coords x-0, y-1, z-7.

But nobody said it had to be spatial. It could also be what you get when you select choice 0 on the first menu, 1 on the second menu and 7 on the next.

Multi-D arrays are ultimately simply about using arrays to create chained numeric mappings to specific values. In the end it's always only the last array in the chain that actually holds values rather than arrays. The indeces can have any meaning we want to give them.

Title: Visualization of N>2-D array?

Body:
I have an array of dimension 5. But, I can't figure out how to visualize that array?

```<code>int[][][][][] array = new int[4][4][4][6][2].
</code>```

Is there a good way to visualize arrays with dimension counts of 3 or more?

Body:
Think of each level of multi-D array access as an address with meaning that leads to something specific.

x[0][1][7];

This could represent whatever's at the space coords x-0, y-1, z-7.

But nobody said it had to be spatial. It could also be what you get when you select choice 0 on the first menu, 1 on the second menu and 7 on the next.

Multi-D arrays are ultimately simply about using arrays to create chained numeric mappings to specific values. In the end it's always only the last array in the chain that actually holds values rather than arrays. The indeces can have any meaning we want to give them.


答:
If you look for a graphical way to represent it in a 3D space what @whatsisname said is the solution. Or the other way around: a cube in which each element is a matrix. It depends on what your data represents.

If you just want to check the data, an expandable 5-level tree should do just fine.

Title: Visualization of N>2-D array?


答:
"Visualizing" beyond 3 dimensions is very difficult, if not impossible to do spatially (although I have friends who swear they can do 4).  But if you want a good idea of how to think of a 5d or even n-d matrix represents data, think of an html source tree.  You have:</p>

```<code>top layer[0]
    stuff in the second layer[0][0]
        stuff in the third layer[0][0][0]
             you get the picture...
        stuff in the third layer[0][0][1]
    stuff in the second layer[0][1]
top layer[1]
    more stuff...
</code>```

Title: Visualization of N>2-D array?

Body:
"Visualizing" beyond 3 dimensions is very difficult, if not impossible to do spatially (although I have friends who swear they can do 4).  But if you want a good idea of how to think of a 5d or even n-d matrix represents data, think of an html source tree.  You have:

top layer[0]
    stuff in the second layer[0][0]
        stuff in the third layer[0][0][0]
             you get the picture...
        stuff in the third layer[0][0][1]
    stuff in the second layer[0][1]
top layer[1]
    more stuff...


问:
Using MVC in a Java app
I need to write a cross-platform GUI application to process (in multiple threads) and visualize fairly large quantities of data. Ideally the application should be relatively fast and look good.

The app's interface will consist of a table widget, a tree widget, and a custom figure-drawing widget. The user will be able to modify the data from any one of these widgets and the changes should be immediately reflected in the other widgets.

Naturally, I am planning to use MVC. However, I normally do all my GUI programming in C++/Qt, and have very limited exposure to Java. So I would really appreciate any advice on how to organize such an app in Java. In particular, should I use Swing or JavaFX? Which widgets would you pick for the job? Could you recommend any books/online tutorials that cover these aspects of the Java platform?

I will greatly appreciate any feedback. Thanks!

(this question was originally posted on Stack Overflow, but this site was suggested as a more appropriate place to ask it)

答:
The widgets that you require can be found in both Swing or SWT. The documentation contains examples of components (Swing) or widgets (SWT) so it will be fairly easy to identify them.

Swing is GUI library included in JDK and built from scratch. SWT is an external one and the components are based on native ones.

As for MVC, they both have support for it. In Swing you have a Model for each component that practically provides the underlying data. The component itself is both the View and the Controller.

Title: Using MVC in a Java app


答:
That really depends on the content of cells. But if you really want to visualize the content, you don't need to see at once 5D array of high precision values.

Define few (2-5) efficiently different ranges to where could belong values.  And make 2 of your dimensions as x and y, and other three - interpret as colors - R,G,B. And in every point (x,y,r,g,b) you can have a value of the range. Of course, a looker needs time to understand the image, but he would need it for every sort of 5D image.

Title: Visualization of N>2-D array?


答:
I don't think it makes sense to visualize array in any sort of real 'spatial' sense.  Ultimately, it's all getting mapped to 'flat' memory addresses.

If you really had to do it - maybe something like this?

(http://sp-productions.zxq.net/c++%20tutorial2.html)

Still, I'd just avoid trying to think of it as anything physical.  Because....well, it isn't.

If you think of it as an array of arrays (...of arrays...) you can describe any nd array.

A two dimensional array is just an array where each element represent it's own array.

A three dimensional array is just an array where each element represent an array where each element represents an array.
etc...etc...

Title: Visualization of N>2-D array?


问:
Writing proprietary and possibly closed source software while avoiding license infractions
I am starting a software project that I want to have the option to keep it proprietary.  However, since I generally use a Linux environment, I want to know: How do people write proprietary software in Linux and not violate the GPL/LGPL/etc licenses that seem to restrict uses of libraries needed to build the project?

Also, does using an unmodified LGPL library in my code require releasing it as open-source (I understand that open-source and proprietary are different beasts)?

And I know I'm going to be branded a heathen for asking, but can I use unmodified open-source libraries in my project but still keep the code that is mine closed-source?

答:
There is an interesting publication on this topic:

Citation:

Maria Kechagia, Diomidis Spinellis, and Stephanos Androutsellis-Theotokis. Open source licensing across package dependencies. In Costas Vassilakis and Nikolaos Tselikas, editors, PCI 2010: Proceedings of 14th Panhelenic Conference on Informatics, pages 27–32, Los Alamitos, CA, USA, September 2010. IEEE Computer Society.

Abstract:

Licensing dependencies among open source software (oss) packages reveal a lot about software compatibility relationships and the practicalities of oss licensing. There is, however, limited information on these in the literature. In this paper, we discuss various aspects of oss licensing, and we present an empirical study on FreeBSD ports collections concerning their licensing dependencies, in an attempt to identify specific patterns. Our results highlight different types of dependencies, that could be used to explain, or even guide the license selection process of oss projects.

Here is the doi number doi:10.1109/PCI.2010.28


问:
Rails generators for subscription and payment processing services?
I've been thinking about making a generator for managing subscriptions with options for a couple different payment processing services, it is something that I would use. Are there any existing examples of this, or any thoughts on a generator. I thought it might work like the scaffold function, similar to the authentication function in nifty-generators.

EDIT: Also, It seems that there should be a lot of security concerns when implementing payment processing, having a consistent and common way to generate this would let me make sure best practices and security are followed the same in all my apps.

答: Take a look at the open source example application for a Rails Membership Site with Stripe or Rails Membership Site with Recurly from the RailsApps project. Both are generated by the  Rails Composer tool. You could use the rails_apps_composer gem to create application templates to handle other billing services (but Stripe and Recurly may be sufficient).


答:
In general, when writing software that uses third-party libraries you need to be aware of the licences under which the third-party software is released and how that affects your own software.

The GPL licence is considered an infectious licence in the sense that if your project includes GPL-licensed code in any way, your code must also be released under the GPL licence (possibly in addition to other licenses).

The LGPL licence was created to take away the infectiousness of the GPL licence. Roughly speaking, if you use a LGPL licensed library in your project you can use any licence you like for your own code (even a closed-source one) as long as the end-user can replace the LGPL licensed library with a different, compatible, one.

For other licenses, you will have to check the licence itself, but in general, MIT and BSD-derived licenses tend to be more permissive than (L)GPL.

Disclaimer: IANL, TINLA

Title: Writing proprietary and possibly closed source software while avoiding license infractions

Body:
I am starting a software project that I want to have the option to keep it proprietary.  However, since I generally use a Linux environment, I want to know: How do people write proprietary software in Linux and not violate the GPL/LGPL/etc licenses that seem to restrict uses of libraries needed to build the project?

Also, does using an unmodified LGPL library in my code require releasing it as open-source (I understand that open-source and proprietary are different beasts)?

And I know I'm going to be branded a heathen for asking, but can I use unmodified open-source libraries in my project but still keep the code that is mine closed-source?


答:
I believe that 'kicking around' the concerns with a few smart people helps.  There needs to be specific information.  Is it s 24x7x365 website?  LoB app?  Where is it running or hosted?

Once you get into the core objectives and desired outcomes, others can help to focus and direct your attention.  Your code might be the best code ever written for one specific task - or the worst.  It really doesn't matter - how does that affect the desired goal?


问:
Proper workaround for multiple inheritence in Java (Android)
I have a conceptual problem with a proper implementation of code which seems require multiple  inheritance, that would not be a problem in many OO languages, but as the project is for Android, there is no such thing like multiple extends.

I have a bunch of activities, derived from different base classes, such as simple Activity, TabActivity, ListActivity, ExpandableListActivity, etc. Also I have some code fragments which I need to place into onStart, onStop, onSaveInstanceState, onRestoreInstanceState and other standard event handlers in all activities.

If I have a single base class for all activities, I'd place the code into a special intermediate derived class, and then create all activities extending it. Unfortunately, this is not the case, because there are multiple base classes. But placing the same portions of code into several intermediate classes is not a way to go, imho.

Another approach could be to create a helper object and delegate all calls of the abovementioned events to the helper. But this requires the helper object to be included, and all handlers to be redefined in all intermediate classes. So there is no much difference to the first approach here - still a lot of code duplicates.

If a similar situation occured under Windows, I'd subclass base class (something that "corresponds" to the Activity class in Android) and trap appropriate messages there (in a single place).

What can be done in Java/Android for this? I know there is interesting tools such as Java instrumentation (with some real examples), but I'm not a Java guru, and not sure if it's worth trying in this specific case.

If I missed some other decent solutions, please, mention them.

UPDATE:

For those who may be interested in solving the same problem in Android I've found a simple workaround. There exist the Application class, which provides, among other things, the interface ActivityLifecycleCallbacks. It does exactly what I need allowing us to intercept and add some value into important events for all activities. The only drawback of this method is that it's available starting from API level 14, which is not enough in many cases (support for API level 10 is a typical requirement today).

答:
It is true that Java doesn't allow multiple-inheritance, but you could simulate it more or less by making each one of your SomeActivity subclasses extend the original Activity class.

You'll have something like:

```<code>public class TabActivity extends Activity {
    .
    .
    .
}
</code>```

Body:
It is true that Java doesn't allow multiple-inheritance, but you could simulate it more or less by making each one of your SomeActivity subclasses extend the original Activity class.

You'll have something like:

public class TabActivity extends Activity {
    .
    .
    .
}


答:
Go with a Model-view-presenter pattern instead. You can view a good MVP example in Swing here via the mvp4j project.

While not Swing, I'd also check out the MVP articles over at the GWT Google Developers site for further insight on this pattern and how to apply it in Java; the same design principals stand regardless of the framework and GWT is very similar to Swing.

A quick breakdown of how MVP works:

View: A class that strictly contains your GUI components. No awareness of logic or model, not even event handlers. This makes views very dumb, yet very disposable and changeable.

Presenter: A class that handles your application logic. A presenter will bind to one (or more) view classes and handle all the necessary application logic and model control.

Model: Your data model objects. It's best to keep these as POJO-like as possible (plain old java objects).

When implemented correctly, MVP will make your application very decoupled and allow you to make modifications without disturbing other areas of your application.

Edit: Based on your decision to use JavaFX, I'd recommend checking out the following articles

Effective JavaFX Architecture

JavaFX And MVP – A Smörgåsbord Of
Design Patterns

JavaFX MVP Example

Title: Using MVC in a Java app

Body:
I need to write a cross-platform GUI application to process (in multiple threads) and visualize fairly large quantities of data. Ideally the application should be relatively fast and look good.

The app's interface will consist of a table widget, a tree widget, and a custom figure-drawing widget. The user will be able to modify the data from any one of these widgets and the changes should be immediately reflected in the other widgets.

Naturally, I am planning to use MVC. However, I normally do all my GUI programming in C++/Qt, and have very limited exposure to Java. So I would really appreciate any advice on how to organize such an app in Java. In particular, should I use Swing or JavaFX? Which widgets would you pick for the job? Could you recommend any books/online tutorials that cover these aspects of the Java platform?

I will greatly appreciate any feedback. Thanks!

(this question was originally posted on Stack Overflow, but this site was suggested as a more appropriate place to ask it)


答:
I am afraid you can-t implement your classsystem without codeduplication in android/java.

However you can minimize codeduplication if you combine special intermediate derived class with
composite helper object. This is called the Decorator_pattern:

```<code>    class ActivityHelper {
        Activity owner;
        public ActivityHelper(Activity owner){/*...*/}
        onStart(/*...*/){/*...*/}
    }

    public class MyTabActivityBase extends TabActivity {
        private ActivityHelper helper;
        public MyTabActivityBase(/*...*/) {
            this.helper = new ActivityHelper(this);
        }

        protected void onStart() {
            super.onStart();
            this.helper.onStart();
        }
        // the same for onStop, onSaveInstanceState, onRestoreInstanceState,...
    }

    Public class MySpecialTabActivity extends MyTabActivityBase  {
       // non helper logic goes here ....
    }
</code>```

so every base class you create an intermediate baseclass that delegates its calls to the helper.
The intermediate basesclasses are identical except the the baseclase where they inherit from.

Title: Proper workaround for multiple inheritence in Java (Android)

Body:
I have a conceptual problem with a proper implementation of code which seems require multiple  inheritance, that would not be a problem in many OO languages, but as the project is for Android, there is no such thing like multiple extends.

I have a bunch of activities, derived from different base classes, such as simple Activity, TabActivity, ListActivity, ExpandableListActivity, etc. Also I have some code fragments which I need to place into onStart, onStop, onSaveInstanceState, onRestoreInstanceState and other standard event handlers in all activities.

If I have a single base class for all activities, I'd place the code into a special intermediate derived class, and then create all activities extending it. Unfortunately, this is not the case, because there are multiple base classes. But placing the same portions of code into several intermediate classes is not a way to go, imho.

Another approach could be to create a helper object and delegate all calls of the abovementioned events to the helper. But this requires the helper object to be included, and all handlers to be redefined in all intermediate classes. So there is no much difference to the first approach here - still a lot of code duplicates.

If a similar situation occured under Windows, I'd subclass base class (something that "corresponds" to the Activity class in Android) and trap appropriate messages there (in a single place).

What can be done in Java/Android for this? I know there is interesting tools such as Java instrumentation (with some real examples), but I'm not a Java guru, and not sure if it's worth trying in this specific case.

If I missed some other decent solutions, please, mention them.

UPDATE:

For those who may be interested in solving the same problem in Android I've found a simple workaround. There exist the Application class, which provides, among other things, the interface ActivityLifecycleCallbacks. It does exactly what I need allowing us to intercept and add some value into important events for all activities. The only drawback of this method is that it's available starting from API level 14, which is not enough in many cases (support for API level 10 is a typical requirement today).

Body:
I am afraid you can-t implement your classsystem without codeduplication in android/java.

However you can minimize codeduplication if you combine special intermediate derived class with
composite helper object. This is called the Decorator_pattern:

    class ActivityHelper {
        Activity owner;
        public ActivityHelper(Activity owner){/*...*/}
        onStart(/*...*/){/*...*/}
    }

    public class MyTabActivityBase extends TabActivity {
        private ActivityHelper helper;
        public MyTabActivityBase(/*...*/) {
            this.helper = new ActivityHelper(this);
        }

        protected void onStart() {
            super.onStart();
            this.helper.onStart();
        }
        // the same for onStop, onSaveInstanceState, onRestoreInstanceState,...
    }

    Public class MySpecialTabActivity extends MyTabActivityBase  {
       // non helper logic goes here ....
    }

so every base class you create an intermediate baseclass that delegates its calls to the helper.
The intermediate basesclasses are identical except the the baseclase where they inherit from.


答:
Pretty much any self-help book you pick up on communication is going to give you some variation of this:

Seek first to understand, then to be understood

That comes from the 7 habits book, but they're all some variation of the "active listening" method.  The goal is not just to understand, but to communicate back to them that you understood.

Once I think I have a good idea of what they need (stay away from what they want particularly if they start describing implementation details - that's your job not theirs), I give them examples of stories of various people using the system, and see if that jives with them.

Then I implement that, fully expecting that once they see the feature, they'll actually realize that's not exactly what they want.  Keep everything flexible.  The only constant is change.  I usually get most of the rough edges worked out after the second quick update after the initial one, but I always find I'm asymptotically approaching some ideal that I can never reach.  Eventually you need to let the unimportant things go and move on to higher value targets.


答:
Starting in Android 3.0, it may be possible to solve this elegantly by using a Fragment. Fragments have their own lifecycle callbacks and can be placed inside an Activity. I'm not sure this will work for all the events though.

Another option I'm also not sure about (lacking in-depth Android know-how) might be to use a Decorator in the opposite way k3b suggests: create an ActivityWrapper whose callback methods contain your common code and then forward to a wrapped Activity object (your actual implementation classes), and then have Android start that wrapper.


答:
You should prefer composition over inheritance. A nice example is the IExtension "pattern" in the .NET WCF framework. Baiscally you have 3 interfaces, IExtension, IExtensibleObject and IExtensionCollection. You can then compose the different behaviors with an IExtensibleObject object by addig IExtension instances to it's Extension IExtensionCollection property. In java it should look something like that, not however that you have to create your own IExtensioncollection implementation that calls the attach and detach methods when items are being added/removed. Also note that it is up to you to define the extension points in your extensible class The example uses an event-like callback mechanism:

```<code>import java.util.*;

interface IExtensionCollection<T> extends List<IExtension<T>> {
    public T getOwner();
}

interface IExtensibleObject<T> {
    IExtensionCollection<T> getExtensions();
}

interface IExtension<T> {
    void attach(T target);
    void detach(T target);
}

class ExtensionCollection<T>
    extends LinkedList<IExtension<T>>
    implements IExtensionCollection<T> {

    private T owner;
    public ExtensionCollection(T owner) { this.owner = owner; }
    public T getOwner() { return owner; }
    public boolean add(IExtension<T> e) {
        boolean result = super.add(e);
        if(result) e.attach(owner);
        return result;
    }
    // TODO override remove handler
}

interface ProcessorCallback {
    void processing(byte[] data);
    void processed(byte[] data);
}

class Processor implements IExtensibleObject<Processor> {
    private ExtensionCollection<Processor> extensions;
    private Vector<ProcessorCallback> processorCallbacks;
    public Processor() {
        extensions = new ExtensionCollection<Processor>(this);
        processorCallbacks = new Vector<ProcessorCallback>();
    }
    public IExtensionCollection<Processor> getExtensions() { return extensions; }
    public void addHandler(ProcessorCallback cb) { processorCallbacks.add(cb); }
    public void removeHandler(ProcessorCallback cb) { processorCallbacks.remove(cb); }

    public void process(byte[] data) {
        onProcessing(data);
        // do the actual processing;
        onProcessed(data);
    }
    protected void onProcessing(byte[] data) {
        for(ProcessorCallback cb : processorCallbacks) cb.processing(data);
    }
    protected void onProcessed(byte[] data) {
        for(ProcessorCallback cb : processorCallbacks) cb.processed(data);
    }
}

class ConsoleProcessor implements IExtension<Processor> {
    public ProcessorCallback console = new ProcessorCallback() {
        public void processing(byte[] data) {

        }
        public void processed(byte[] data) {
            System.out.println("processed " + data.length + " bytes...");
        }
    };
    public void attach(Processor target) {
        target.addHandler(console);
    }
    public void detach(Processor target) {
        target.removeHandler(console);
    }
}

class Main {
    public static void main(String[] args) {
        Processor processor = new Processor();
        IExtension<Processor> console = new ConsoleProcessor();
        processor.getExtensions().add(console);

        processor.process(new byte[8]);
    }
}
</code>```

This approach has the benefit of extension reuse if you manage to extract common extension points between your classes.

Body:
You should prefer composition over inheritance. A nice example is the IExtension "pattern" in the .NET WCF framework. Baiscally you have 3 interfaces, IExtension, IExtensibleObject and IExtensionCollection. You can then compose the different behaviors with an IExtensibleObject object by addig IExtension instances to it's Extension IExtensionCollection property. In java it should look something like that, not however that you have to create your own IExtensioncollection implementation that calls the attach and detach methods when items are being added/removed. Also note that it is up to you to define the extension points in your extensible class The example uses an event-like callback mechanism:

import java.util.*;

interface IExtensionCollection<T> extends List<IExtension<T>> {
    public T getOwner();
}

interface IExtensibleObject<T> {
    IExtensionCollection<T> getExtensions();
}

interface IExtension<T> {
    void attach(T target);
    void detach(T target);
}

class ExtensionCollection<T>
    extends LinkedList<IExtension<T>>
    implements IExtensionCollection<T> {

    private T owner;
    public ExtensionCollection(T owner) { this.owner = owner; }
    public T getOwner() { return owner; }
    public boolean add(IExtension<T> e) {
        boolean result = super.add(e);
        if(result) e.attach(owner);
        return result;
    }
    // TODO override remove handler
}

interface ProcessorCallback {
    void processing(byte[] data);
    void processed(byte[] data);
}

class Processor implements IExtensibleObject<Processor> {
    private ExtensionCollection<Processor> extensions;
    private Vector<ProcessorCallback> processorCallbacks;
    public Processor() {
        extensions = new ExtensionCollection<Processor>(this);
        processorCallbacks = new Vector<ProcessorCallback>();
    }
    public IExtensionCollection<Processor> getExtensions() { return extensions; }
    public void addHandler(ProcessorCallback cb) { processorCallbacks.add(cb); }
    public void removeHandler(ProcessorCallback cb) { processorCallbacks.remove(cb); }

    public void process(byte[] data) {
        onProcessing(data);
        // do the actual processing;
        onProcessed(data);
    }
    protected void onProcessing(byte[] data) {
        for(ProcessorCallback cb : processorCallbacks) cb.processing(data);
    }
    protected void onProcessed(byte[] data) {
        for(ProcessorCallback cb : processorCallbacks) cb.processed(data);
    }
}

class ConsoleProcessor implements IExtension<Processor> {
    public ProcessorCallback console = new ProcessorCallback() {
        public void processing(byte[] data) {

        }
        public void processed(byte[] data) {
            System.out.println("processed " + data.length + " bytes...");
        }
    };
    public void attach(Processor target) {
        target.addHandler(console);
    }
    public void detach(Processor target) {
        target.removeHandler(console);
    }
}

class Main {
    public static void main(String[] args) {
        Processor processor = new Processor();
        IExtension<Processor> console = new ConsoleProcessor();
        processor.getExtensions().add(console);

        processor.process(new byte[8]);
    }
}

This approach has the benefit of extension reuse if you manage to extract common extension points between your classes.


答:
In addition to other answers, I'd recommend going to a developer conference.

This will expose you to a lot of topics and people that will make you think about your own app and workplace. Especially as they will talk about what works and not for then, and issues that come up. There's a big likelihood that there's some overlap with your app.

Preferably, take 3 days for this. I've found that to be long enough to get the necessary mental distance to my own work and look at it through the eyes of a larger community (so to speak), rather than my own.

Incidentally, this also applies to teams of people too, since groupthink can happen anywhere.

Finally, if you don't get approval for this, say once per year, change job.


答:
I think you're trying to avoid the wrong type of code duplication.  I believe Michael Feathers wrote an article about this but unfortunately I can't find it.  The way he describes it is you can think of your code as having two parts like an orange: The rind and the pulp.  The rind is the stuff like method declarations, field declarations, class declarations, etc.  The pulp is the stuff inside these methods; the implementation.

When it comes to DRY, you want to avoid duplicating pulp.  But often in the process you create more rind.  And that's ok.

Here's an example:

```<code>public void method() { //rind
    boolean foundSword = false;
    for (Item item : items)
        if (item instanceof Sword)
             foundSword = true;
    boolean foundShield = false;
    for (Item item : items)
        if (item instanceof Shield)
             founShield = true;
    if (foundSword && foundShield)
        //...
}  //rind
</code>```

This can be refactored into this:

```<code>public void method() {  //rind
    if (foundSword(items) && foundShield(items))
        //...
} //rind

public boolean foundSword(items) { //rind
    return containsItemType(items, Sword.class);
} //rind

public boolean foundShield(items) { //rind
    return containsItemType(items, Shield.class);
} //rind

public boolean containsItemType(items, Class<Item> itemClass) { //rind
    for (Item item : items)
        if (item.getClass() == itemClass)
             return true;
    return false;
} //rind
</code>```

We added a lot of rind in this refactoring.  But, the second example has a much cleaner method() with less DRY violations.

You said you'd like to avoid the decorator pattern because it leads to code duplication.  If you look at the image in that link you'll see it will only duplicate the operation() signature (ie: rind).  The operation() implementation (pulp) should be different for each class.  I think your code will end up cleaner as a result and have less pulp duplication.

Body:
I think you're trying to avoid the wrong type of code duplication.  I believe Michael Feathers wrote an article about this but unfortunately I can't find it.  The way he describes it is you can think of your code as having two parts like an orange: The rind and the pulp.  The rind is the stuff like method declarations, field declarations, class declarations, etc.  The pulp is the stuff inside these methods; the implementation.

When it comes to DRY, you want to avoid duplicating pulp.  But often in the process you create more rind.  And that's ok.

Here's an example:

public void method() { //rind
    boolean foundSword = false;
    for (Item item : items)
        if (item instanceof Sword)
             foundSword = true;
    boolean foundShield = false;
    for (Item item : items)
        if (item instanceof Shield)
             founShield = true;
    if (foundSword && foundShield)
        //...
}  //rind

This can be refactored into this:

public void method() {  //rind
    if (foundSword(items) && foundShield(items))
        //...
} //rind

public boolean foundSword(items) { //rind
    return containsItemType(items, Sword.class);
} //rind

public boolean foundShield(items) { //rind
    return containsItemType(items, Shield.class);
} //rind

public boolean containsItemType(items, Class<Item> itemClass) { //rind
    for (Item item : items)
        if (item.getClass() == itemClass)
             return true;
    return false;
} //rind

We added a lot of rind in this refactoring.  But, the second example has a much cleaner method() with less DRY violations.

You said you'd like to avoid the decorator pattern because it leads to code duplication.  If you look at the image in that link you'll see it will only duplicate the operation() signature (ie: rind).  The operation() implementation (pulp) should be different for each class.  I think your code will end up cleaner as a result and have less pulp duplication.


问:
What tools or techniques are useful for describing an unfamiliar codebase?
When manually inspecting unfamiliar code (to review or modify), I seem to have three options.

A top-down read of the code, choosing each next source file by how fundamental the filename seems.  I usually end up reading nearly everything.  Some files twice.

A breadth-first read, where I find and read all of the invoking method with minimal understanding.  Then read all the functions that function called, and so on.  My mental stack tends to overflow if I make it a few calls deep.

A depth-first read, where I step through all the code in a debugger, unsure of whether this will take 8 minutes or 8 hours.

Once I've read enough of the code to have a fairly solid understanding of what it's doing, I often reflect that I've read 80% or more of the codebase, while the fundamental code is 20% or less.  I've wasted a lot of time.

What tools are useful for getting a quick grasp of unfamilar code?  Are there any tools that can give a "big picture" of the critical code path and allow me to drill down to the details of any one part?

答:
The best thing, of course, is for someone who does know the code base to walk you through it.  If that is not an option, then there are some tools that can help you.

VisualStudio can automatically generate a UML class diagram of a code base.  At the very least it will show you the class hierarchies.

Doxygen can be extremely helpful. Even if the code does not have the doxygen-style comments, doxygen can still generate readable documentation, class diagrams, and call graphs, which can be very helpful for finding your way around an unfamiliar code base.

Generally, you also want to be using a full-featured IDE, where you can right-click anything and "go to definition".  This can save you lots of time, compared with using grep on lots of files in a complex directory structure.

Another important thing, depending on how long you will have to deal with the code. If there are unit tests, then look through the tests.  If there are no tests, start writing them.  Form a hypothesis about what a particular class or function does, and write a test to test it. This takes a lot of discipline, but it is a great way to get answers about what's happening in the code.


答:
This is a more drastic approach. This technique may be useful for a project that has many classes that are not organized into meaningful namespaces.

The goal of this exercise is to discover the class relationship. Make a throwaway clone of the project, and then try to put some classes into namespaces. To save time on repeated attempts, use some Regex file processing tools to automate this change.

This will cause a lot of compiler errors. In the process of fixing these errors, one will have a better grasp how these classes depend on each other, and decide what classes could be put into the same namespace.

This technique is useful in that one can apply it even with little understanding of the project's code organization. With this comes the risk that some classes could be misplaced by this technique due to misunderstanding.

Title: What tools or techniques are useful for describing an unfamiliar codebase?

Body:
When manually inspecting unfamiliar code (to review or modify), I seem to have three options.

A top-down read of the code, choosing each next source file by how fundamental the filename seems.  I usually end up reading nearly everything.  Some files twice.

A breadth-first read, where I find and read all of the invoking method with minimal understanding.  Then read all the functions that function called, and so on.  My mental stack tends to overflow if I make it a few calls deep.

A depth-first read, where I step through all the code in a debugger, unsure of whether this will take 8 minutes or 8 hours.

Once I've read enough of the code to have a fairly solid understanding of what it's doing, I often reflect that I've read 80% or more of the codebase, while the fundamental code is 20% or less.  I've wasted a lot of time.

What tools are useful for getting a quick grasp of unfamilar code?  Are there any tools that can give a "big picture" of the critical code path and allow me to drill down to the details of any one part?


问:
Should a programmer take writing lessons to enhance code expressiveness?
Given that programmers are authors and write code to express abstract thoughts and concepts, and good code should be read by other programmers without difficulties and misunderstandings, should a programmer take writing lessons to write better code?

Abstracting concepts and real world problems/entities is an important part of writing good code, and a good mastery of the language used for coding should allow the programmer to express his thoughts more easily, or in a better way. Besides, when trying to write or rewrite some code to make it better, much time can be spent in deciding the names for functions, variables or data structures.

I think this could also help to avoid writing code with more than one meaning, often cause of misunderstanding between different programmers. Code should always express clearly its function unambiguously.

答:
There is certainly a big difference between writing code and writing prose.

In prose the sentences are connected (or separated) by time (the way they follow each other in order to reach an end or meaning) but in (efficient) code you can (re)load parts of the 'story' from tables with repeatable actions/responses. So, the interaction with the reader (in prose) or user (of code) is totally different.

In another way writing 'nice' prose and writing 'nice' code are similar: learning to write (code or prose) is a process which involves a lot of making mistakes (or thinking/testing about improvements, or reformulating) to get it 'elegant'.

I think the chemical periodical system of elements is elegant, because of the very compact way it describes some fundamental properties of basic materials we use, a bit like efficient code but it is certainly not prose. A joke has a lot of prose qualities (getting you into a certain mood, keeping that mood and then change it, when unexpected) but that's an awfull coding practice.

But both types of writing ask for craftsmanship.


问:
Working with clients who don't know what they want
I have recently started a job that has me working on an existing system. It requires tweaks and updates as well as new code. I have done several maintainance/feature adding projects now, and several of them have ended up being significantly different from what was actually requested. So, I had to program the item several times to get it to where the requester wanted.

Now, I don't mind reprogramming the feature if that's what needs to be done. However, I would like to decrease turnaround time on my projects. The bottleneck seems to be in the requester's perception of what needs to be done. Do you have any ideas on what I could do to figure out what the requester needs more quickly?

答:
First of all, you should accept the fact that clients don't really know what they're looking for until they see it. They might tell you right now that they need feature X. Show them feature X then they'll realize that what they really need is feature Y or another variation of feature X.

A good way to figure out what the customer really wants more quickly is by embracing and following the Agile Manifesto, which focuses on communication and customer collaboration. Divide the development cycle into iterations and show the client a prototype of the feature every end of the iteration. That way, you'll get immediate feedback and change it, according to the feedback from the client, without having to invest too much resource on the feature. That way, both you and the client will be happy with the outcome of the product.

I'm pretty sure the transition will be hard for your team or your company but it's one the best ways to cope with quickly changing requirements.


问:
WCF service as a proxy for publishing real-time data to a WPF/MVVM clients
I've been tasked with creating a dashboard application to show real time updates for our servers. The raw data comes in from an XML file on our intranet which I need to parse and present to the user.

It is not an option to have every user of the dashboard pull this XML file at the same time for their updates. From what I have been reading, I need to use a WCF service to consume the XML file server side and then have it push updates to all clients who are looking at the service.

I need it to be scalable, there will be around 20 concurrent users at the start but I will need to scale to hundreds in the future. I will need to update from the XML file every 30 seconds to 1 minute.

Am I on the right track with WCF? Are there other options that I should consider?

答:
Are you intending that the WCF service will read the XML, perform processing on it, and serve up massaged data to the WPF clients?

If not, I'm not sure what benefit you will get from a WCF service. Why not just have the XML file on a webserver and have the WPF clients make an HTTP request for it?


答: A better approach may be to use SignalR, you could create a SignalR Hub which the clients connect to and it could push the data to the connected clients rather than them having to poll for it.</p>

Title: WCF service as a proxy for publishing real-time data to a WPF/MVVM clients

Body:
I've been tasked with creating a dashboard application to show real time updates for our servers. The raw data comes in from an XML file on our intranet which I need to parse and present to the user.

It is not an option to have every user of the dashboard pull this XML file at the same time for their updates. From what I have been reading, I need to use a WCF service to consume the XML file server side and then have it push updates to all clients who are looking at the service.

I need it to be scalable, there will be around 20 concurrent users at the start but I will need to scale to hundreds in the future. I will need to update from the XML file every 30 seconds to 1 minute.

Am I on the right track with WCF? Are there other options that I should consider?


答:
This is all very subjective as multiple different technologies will be able to serve your needs.

Like others, I'll probably just recommend the technology I'd personally prefer for such a project, which would be JavaFX.

Reasons I would recommend JavaFX are:

In-built properties and binding make it easy to wire up parts of your GUI for automatic updates.

Quality graphical design tool.

Separation of UI component layout from control logic using FXML.

High quality, hardware accelerated, platform independent rendering architecture.

Wide variety of supported platforms and systems.

Support for touch interaction.

Separation of style from code using CSS.

SceneGraph based retained rendering model rather than a direct draw model.

Quality documentation and support forums plus help available via  StackOverflow and a web blogging community.

Wide variety of quality pre-built controls.

Media support.

Modern, performant HTML5 engine.

Embeddable in Swing applications if needed, so you can still make use of Swing based frameworks.

Embeddable in SWT applications if needed, so you can still make us of SWT based frameworks.

Ability to support immediate mode rendering if required.

Effects framework.

Animation framework.

Graphing framework.

Open source development.

Excellent sample program.

Public issue tracker and responsive developers, doing active, on-going development so that new features and bugs get addressed in a timely way.

Backing of a major company prepared to invest considerable resources to make the project successful.

Deployable via native platform installers and executables.

Able to utilize all of the features of the massive JDK and java based libraries and projects.

Can be used from a variety of programming languages, such as Scala, Groovy and Ruby.

Nice interactive development and debugging utilities as well as the ability to use a standard Java debugger to debug your program.

Quality layout managers.

JavaFX has been designed to take advantage of Java 8 lambdas.

JavaFX applications are deployable to commercial app stores.

JavaFX can be programmed using the best IDEs in the world.

Strong concurrency utilities.

OK, I guess the above is a bit of a tangent, but I like to promote JavaFX ;-)

Anyway, to address the specific points in your question:

JavaFX is a cross-platform GUI framework (currently Mac/Windows/Linux).

JavaFX has inbuilt, high quality multiple threading support (the core framework itself is single-threaded as is just about every other GUI platform out there, but you can define your own tasks to be executed concurrently off the GUI thread so that the GUI thread remains responsive).

A well written JavaFX program should have no issues performing well enough to visualize fairly large quantities of data.  Here is a sample JavaFX project which does that.

The ability to style the application via css, make use of visual effects and animation, allows you to work with designers to make your app look great or do it yourself if you have the skills.

JavaFX has a TableView and a TreeView you can use.  There is also a combined TreeTable control which has been developed in preparation for the Java 8 release.

The custom figure drawing widget could use scene graph shapes or a direct draw canvas - it's really just a matter of coding style and preference.

JavaFX's properties and binding facilities coupled with it's event listener frameworks makes it trivial to modify data using one control and have the changes immediately reflected in other controls.

For MVC style development, you can write your model using plain java objects, define your view using the FXML markup language (created using the SceneBuilder graphical layout tool if desired) and define your control logic in Java (or another scripting language if you prefer), plus you should separate your style from your logic by using CSS.

As you have limited exposure to Java, the learning curve will be significant.  There are excellent Java tutorials in addition to the JavaFX tutorials I linked to earlier which can help with this.  JavaFX core code uses only facilities available in the JDK, so to use JavaFX you don't need to learn a lot of additional libraries and frameworks (as you would if you were learning JavaEE for instance).  So those two tuotorial sites provide most information you need to get up to speed.

For app organization, if you have a complex application and need the backing of a complete, proven client application framework and don't mind doing a lot of extra learning, then you can embed JavaFX in the Eclipse RCP or NetBeans RCP, which, according to their pages could save you years of development time.  I'd only advise looking at such platforms if your needs justify it though, because for small to medium size projects, it will probably be simpler to code the stuff up directly in JavaFX without the complex client platform frameworks such as Eclipse and NetBeans.

As to whether you should use Swing or JavaFX, I'm not really the most objective person to answer that.  JavaFX definitely has shortcomings which would become apparent to you as you start to use it (as does Swing).

For online tutorials, I've linked to most relevant ones. There is a nice tutorial set for a complete app.

The books Pro JavaFX 2 and JavaFX 2.0 Introduction by Example are highly rated.

Title: Using MVC in a Java app


问:
Should I fix small issues or let them go?
I ran into the following issue where a keyboard shortcut I was used to was no longer working in Ubuntu. That's just an example. For programming, this kinds of thing happens a lot, but it also happens in any aspect of work and life.

I'm always tempted to fix it right away because I have an idea of what might fix it in a few minutes. Of course, a lot of times the idea is wrong, and much more effort is required.

I basically go through an optimization process where I continuously ask myself "Did I spend too much time looking for a fix already?" in trying to decide whether to abandon the effort.

I think any one issue can be abandoned, but I think that if I do it for all of them, my life will be a mess of inefficiencies.

Question: How do you effectively approach this temptation of small problems?

As I wrote up in the above rambling blog post the pros and cons for the decision to pursue any one individual issue are:

Pros:

I fix the small problem the "right" way, so I don’t have to settle
for a half-ass sweep-under-the-rug solution.

I get to spend an hour
being open to the possibility of learning new things relevant to my
work and exchanging information with the community of fellow Linux
users. The computer world evolves on a daily basis, with new
technologies, approaches, ideas constantly emerging. So, it’s
important to stay connected to the latest developments.

I get to
practice persevering in dealing with frustrating issues.

Cons:

It is not guaranteed that I find a solution.

It always takes longer than you thin. At first, it seems like the fix
would not take more than 5 minutes, and when it does (50+% of the
time), I become progressively more invested in it as time goes on.
It’s the same principle that keeps you gambling in a Casino until all
your money is gone.

Perfectionism is an addiction. We live in a world of inefficiencies
that could be easily optimized if you just give it a few minutes.
Sometimes it does take minutes, but sometimes it may take days. The
more you feed this addiction, the harder it becomes to exist
peacefully in an inefficient world.

答:
Let them go.

Concentrate on the bigger things. You'll end up wasting half your time on unimportant things. It's not a bad thing to work on a smaller issue itself, but it could be if you end up missing out on the more important stuff.

Get comfortable with your own personality so that you are aware of this tendency. Don't beat yourself up about it, don't fret, but remind yourself occasionally to work on the bigger picture stuff, and that sometimes the smaller things really don't matter.

Remember, software that people use only has to be good enough. It doesn't have to be perfect.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
That real-time means fast.

Stating "The packets need to be processed in real-time." is worthless and the evil twin...answering "How fast does X need to happen ?" with "Real-time" is possibly less than worthless...bordering on stupid rather than ignorant.

Real-time means that, simply put, that function Y will always take X amount of time and that any deviation indicates a serious error. The duration of X does not define "real-time" it could be six microseconds or six days. That you can determine function Y will take X time defines "real-time". Real-time systems are deterministic by this definition.

So knock it off..


答:
For these types of things, I recommend that you file a defect, issue or an enhancement request as appropriate so that it can be tracked, scheduled if need be, and not forgotten.

Get your primary and most important work done before you start tackling the extra.  Not only does this help ensure you hit your own deadlines, it also gives others a chance to evaluate what you have found.

In the end, it might not be worth it, or even desirable to fix it.  Then again, it might.  A little distance/time can help provide the state of mind to best evaluate it.

Title: Should I fix small issues or let them go?

Body:
I ran into the following issue where a keyboard shortcut I was used to was no longer working in Ubuntu. That's just an example. For programming, this kinds of thing happens a lot, but it also happens in any aspect of work and life.

I'm always tempted to fix it right away because I have an idea of what might fix it in a few minutes. Of course, a lot of times the idea is wrong, and much more effort is required.

I basically go through an optimization process where I continuously ask myself "Did I spend too much time looking for a fix already?" in trying to decide whether to abandon the effort.

I think any one issue can be abandoned, but I think that if I do it for all of them, my life will be a mess of inefficiencies.

Question: How do you effectively approach this temptation of small problems?

As I wrote up in the above rambling blog post the pros and cons for the decision to pursue any one individual issue are:

Pros:

I fix the small problem the "right" way, so I don’t have to settle
for a half-ass sweep-under-the-rug solution.

I get to spend an hour
being open to the possibility of learning new things relevant to my
work and exchanging information with the community of fellow Linux
users. The computer world evolves on a daily basis, with new
technologies, approaches, ideas constantly emerging. So, it’s
important to stay connected to the latest developments.

I get to
practice persevering in dealing with frustrating issues.

Cons:

It is not guaranteed that I find a solution.

It always takes longer than you thin. At first, it seems like the fix
would not take more than 5 minutes, and when it does (50+% of the
time), I become progressively more invested in it as time goes on.
It’s the same principle that keeps you gambling in a Casino until all
your money is gone.

Perfectionism is an addiction. We live in a world of inefficiencies
that could be easily optimized if you just give it a few minutes.
Sometimes it does take minutes, but sometimes it may take days. The
more you feed this addiction, the harder it becomes to exist
peacefully in an inefficient world.


问:
Which is better: to include HTML inside PHP code or outside it?
Look at this:

```<code><?php
echo "Hello World";
?>
<br />
<?php
echo "Welcome";
?>
</code>```

And now look at this:

```<code><?php
echo "Hello World";
echo "<br />";
echo "Welcome";
?>
</code>```

Which one of the above examples is considered to better (at least from performance point of view)?.

I know the examples are trivial but I want to follow good practice habits from the beginning so when I have more and more lines they would not affect the performance or whatever in a negative way.

答:
As comment points out, it should be done by templates. But if only your two choice is possible. Case 1 will be better. This is the same concept as android inflating layout by xml , or programmaticlly making the UI. Your
 is a static content from your html and all your server will be doing is to show it. But if you use php, to execute it, this will be using your servers resources and be computing.

This is how it should be done:
index.php:

```<code><?php
include 'header.html';
...
include 'footer.html';
?>
</code>```

header.html and footer.html are templates.

Body:
As comment points out, it should be done by templates. But if only your two choice is possible. Case 1 will be better. This is the same concept as android inflating layout by xml , or programmaticlly making the UI. Your <br/> is a static content from your html and all your server will be doing is to show it. But if you use php, to execute it, this will be using your servers resources and be computing.

This is how it should be done:
index.php:

<?php
include 'header.html';
...
include 'footer.html';
?>

header.html and footer.html are templates.


答:
I feel your pain and find myself in that situation a lot.

I try and do that small stuff "as time allows", but that's very vague.

To the question of how to approach the situation:
Triage them is my approach.

You take a quick look - very quick - and it gets classified as Emergency, Urgent, Routine or Minor.  I often do this list/log in excel.  Emergencies may get done immediately and bypass the rest of the processes.  These are always judgment calls (your 'urgent', my 'routine'!) and the key is to adapt them to the circumstances - classifications in a startup will be very different to those in a more established company.

Then, I do an initial review of the details, the complexity, etc.  I'll frequently review items with the product manager.

Then I enter the our issue tracking system (Pivotal Tracker) and give more thought to priority, effort, details, resources, etc.

Our Ticket Tracking System is then used interactively throughout the day (you even see other peoples 'actions'!).