问:
Implement service layer in MVC
We have a defined service layer hosted in WCF. We are now building a website that will need to use the services functionality. The website is being written in ASP.NET MVC 4 and I'm trying to decide how to reference the WCF service from the MVC app. It's a large complex website and it will be changing on a weekly basis.

My first reaction is to abstract out the service references (About 7 services on this one WCF host) and create a service ref facade library with which the website interacts.

But, I don't know exactly how to use the service facade in MVC. I'm starting to think the Models will be responsible for it because when the controller gets a model, that model should call the service (if needed) and return what the controller asked. I'm trying to avoid having the MVC app know details of the service references. So, I could have a model factory that creates whatever model the controllers need and they can use the service facade to accomplish it.

Is this a good plan, or am I off track?

答:
I would not mix the DTO models you use towards the WCF service with the models you use towards the MVC client. You'll run into mismatches quickly.

Use the controllers to mediate between the two. It's OK to invoke directly on service references from controllers, unless it's hard to work with and a facade will improve things.

(View)Models typically should not do (or 'call') anything apart from providing data to a view. The controller pull it's data out to setup a DTO and invoke an appropriate service method.

Title: Implement service layer in MVC


问:
Storing lots of large strings with frequent "appends" and few reads
In my current project, I need to store a very long ASCII string to each instance of a given object. This string will receive an 2 appends per minute and will not be retrieved so frequently.

The worst case scenario is a 5-10MB string. I'll have thousands of instances of my object and I'm worried that storing all those strings in the filesystem would not be optimal, but I can't think of a better solution.

Can anyone suggest an alternative? Maybe a key-value store? In this case, which one? Any other thoughts?

答:
Heres how I would solve this:

I would store the data as a series of blocks within 2GB files. Each block needs the string ID, the block sequence for that string, file ID and file offset of the previous block and around 2k of data space for writing the string chars into. When the data space for that block is filled, then you assign the next unused block to continue the data stream and post back to the previous block.

For each object string, you need to keep in memory the block sequence, the file handle, file offset, and remaining bytes that can be added to this block.

When you need to recreate the string to read, you know how big the string is, based on block sequence number, and then have to read in the data from each of the blocks.

Based on 1000's of objects with 2 writes a second per object, the disk infrastructure needs to be considered.

ContentLicense: CC BY-SA 3.0


问:
Python productivity VS Java Productivity
Over on SO I came across a question regarding which platform, Java or Python is best for developing on Google AppEngine. Many people were boasting of the increased productivity gained from using Python over Java. One thing I would say about the Python vs Java productivity argument, is Java has excellent IDE's to speed up development whereas Python is really lacking in this area because of its dynamic nature.

So even though I prefer to use Python as a language, I don't believe it gives quite the productivity boost compared to Java especially when using a new framework. Obviously if it were Java vs Python and the only editor you could use was VIM then Python would give you a huge productivity boost but when IDE's are brought into the equation its not as clear cut.

I think Java's merits are often solely evaluated on a language level and often on out dated assumptions but Java has many benefits external to the language itself, e.g the JVM (often criticized but offers huge potential), excellent IDE's and tools, huge numbers of third party libraries, platforms etc..

Question: Does Python, or related dynamic languages, really give the huge productivity boosts often talked about (with consideration given to using new frameworks and working with medium to large applications)?

答:
I find that Python, Ruby, Javascript and SQL are much more productive than compiled languages such as Java because those languages have a very quick feedback loop. You can run a few lines of code on a command line and immediately know if the code is correct or not. If it throws exceptions, you know immediately. With Java you have to compile, package and deploy which can often take minutes for large systems, and this results in a very slow feedback cycle. </p>

<p>The fast feedback cycle lets  you quickly iterate to a good solution, and that is what makes dynamic languages more productive. </p>

ContentLicense: CC BY-SA 4.0

Body:
I find that Python, Ruby, Javascript and SQL are much more productive than compiled languages such as Java because those languages have a very quick feedback loop. You can run a few lines of code on a command line and immediately know if the code is correct or not. If it throws exceptions, you know immediately. With Java you have to compile, package and deploy which can often take minutes for large systems, and this results in a very slow feedback cycle.

The fast feedback cycle lets  you quickly iterate to a good solution, and that is what makes dynamic languages more productive.


问:
should singleton be life-time available or should it be destroyable?
Should the singleton be designed so that it can be created and destroyed at any time in program or should it be created so that it is available in life-time of program. Which one is best practice? What are the advantages and disadvantages of both? <br>
EDIT :- As per the link shared by Mat, the singleton should be static. But then what are the disadvantages of making it destroyable? One advantage is it memory can be saved when it is not useful. </p>

答:
Singletons are completely appropriate solutions to some design problems.  However, how the singleton is implemented matters here.

As a C# example,

```<code>public class MySingleton
{
    static MySingleton()
    {
        Instance = new MySingleton();
    }

    protected MySingleton()
    {
    }

    public MySingleton Instance
    {
        get;
        protected set;
    }

    //  Put public instance members and properties here.
}
</code>```

Would be an example of a singleton that should never be destroyed.  Its possible to have an internal static field to store the singleton reference, and to do a lazy instantiation if the internal value is null.  But you then have to worry about ensuring singlethreaded access to test for null, potentially create and then obtain the singleton instance, just so you could free up the memory from this one object at some point.

It is really bad practice to create singletons by declaring the class static.  It makes object destruction impossible, as well as making it a nightmare for mocking the interface in your unit tests.

Body:
Singletons are completely appropriate solutions to some design problems.  However, how the singleton is implemented matters here.

As a C# example,

public class MySingleton
{
    static MySingleton()
    {
        Instance = new MySingleton();
    }

    protected MySingleton()
    {
    }

    public MySingleton Instance
    {
        get;
        protected set;
    }

    //  Put public instance members and properties here.
}

Would be an example of a singleton that should never be destroyed.  Its possible to have an internal static field to store the singleton reference, and to do a lazy instantiation if the internal value is null.  But you then have to worry about ensuring singlethreaded access to test for null, potentially create and then obtain the singleton instance, just so you could free up the memory from this one object at some point.

It is really bad practice to create singletons by declaring the class static.  It makes object destruction impossible, as well as making it a nightmare for mocking the interface in your unit tests.


问:
Creating an in-house single source software development team
Our company wants to create a single department for all software development efforts (rather than having software development managed by each business unit). Business units would then "outsource" their software needs to this department. What would you setup as concerns/expectations that must be cleared before doing this? For example:

Need agreement between units on how much actual time (FTE) is allocated to each unit

Need agreement on scheduling of staff

need agreement on request procedure if extra time is required by one party

etc...

Have you been in a situation like this as a manager of one unit destined to use this? If so, what were problems you experienced? What would you have or did implement? Same if you were the manager of the shared team.

Please assume, for discussion, that the people concerned know that you can't swap devs in and out on a whim. I don't want to know the disadvantages of this approach; I know them. I want to anticipate issues and know how to mitigate the fallout.

答: What is not clear from your question is WHY they are wanting to do this.  If its simply to have a mangement structure that understands development processes, then the simplest way is to maintain the existing teams, just now inside the one department - and nothing much changes, except the line management structure.  If the reason is to enable "more efficient" use of resources by having developers rapidly context switching between projects more easily, then I would be considering which developers are expendible, and who is essential to delivery.  I would make sure that the majority of the rapid context switching is done by the developers that are the least useful.  When they get fed up of not achieving anything they are likely to leave, and in the mean time, you have managed to keep the most effective developers productive despite higher managements best efforts of sabautage.</p>


问:
Why would companies allow these practices?
Here's a situation that usually happens in some companies:

Announce interesting product X.
Promise a release date.
Release on the promised released date, ready or not.
Users discover and report defects.
Send patch after patch after patch after patch after patch.

My question is:

Ummm, what could be the factors that would lead them to tolerate these undesirable practices?

So, in the name of quality, what can be practically and realistically improved in those practicies?

I can think of time constraints, user feedback, sponsors pressuring the company, lack of money.

答: In my experience as a programmer, a project is never completed. We always have to update/add new features to it. Think about it, the mind of the software developer can never be the same as the end user/consumer. You can never tell what the consumer wants/like, so the best option is to allow them to test and then get feedback (very important) to help you upgrade it. It is a natural phenomenon; so that is why they have to do it.</p>


答:
The main factor that goes into it is that the market will accept it. People are used to the fact that software is released with bugs, so will buy software even if they think it's buggy

Then once that condition exists it's hard to reverse. Think about it from the managerial perspective. We can either ship now, and start making revenue, or carry on sinking money into bug fixes that actually don't affect our ability to sell the software; all the while giving our competitors an opportunity to release their buggy software that people will buy.

As discussed in the book geekonomics, this situation parallels that of the U.S. motor car industry in the 1950s-1960s. In that industry, it took every manufacturer changing their emphasis on safety, both in engineering and marketing, and the threat of government regulation to change how cars were designed and made. So far, that hasn't occurred in software.

Title: Why would companies allow these practices?

Body:
Here's a situation that usually happens in some companies:

Announce interesting product X.
Promise a release date.
Release on the promised released date, ready or not.
Users discover and report defects.
Send patch after patch after patch after patch after patch.

My question is:

Ummm, what could be the factors that would lead them to tolerate these undesirable practices?

So, in the name of quality, what can be practically and realistically improved in those practicies?

I can think of time constraints, user feedback, sponsors pressuring the company, lack of money.


答:
Well, there are software development methodologies designed exactly with the aim to deal with this kind of release cycle. Agile programming and Extreme programming are just a couple of example.

As others noted, this (apparently irrational, apparently chaotic) way to develop software is actually well supported by many rational justifications. It is so common and deep-rooted that the software industry developed a few software development methodologies to deal with it.

As a consequence, it cannot actually be considered a scandal. It is just a matter of life and dealing with it is just a part of our profession. We can just study Agile Dev (or something like that) and learn how to use it effectively to deal with this chaos.

Agile and other similar methodologies actually work quite well. Most programmers think that these methodologies work even much better than many others (apparently better organized, more rational ones). As a matter of fact, Agile and similar methodologies are largely considered the only real way to tame software development in the real world.


答:
Insert them as separate items/rows.
Append them together on read.

This can be done in relational DB or simple file.

Title: Storing lots of large strings with frequent "appends" and few reads

Body:
In my current project, I need to store a very long ASCII string to each instance of a given object. This string will receive an 2 appends per minute and will not be retrieved so frequently.

The worst case scenario is a 5-10MB string. I'll have thousands of instances of my object and I'm worried that storing all those strings in the filesystem would not be optimal, but I can't think of a better solution.

Can anyone suggest an alternative? Maybe a key-value store? In this case, which one? Any other thoughts?


问:
Is it a bad practice to include all the enums in one file and use it in multiple classes?
I'm an aspiring game developer, I work on occasional indie games, and for a while I've been doing something which seemed like a bad practice at first, but I really want to get an answer from some experienced programmers here.

Let's say I have a file called enumList.h where I declare all the enums I want to use in my game:

```<code>// enumList.h

enum materials_t { WOOD, STONE, ETC };
enum entity_t { PLAYER, MONSTER };
enum map_t { 2D, 3D };
// and so on.

// Tile.h
#include "enumList.h"
#include <vector>

class tile
{
    // stuff
};
</code>```

The main idea is that I declare all enums in the game in 1 file, and then import that file when I need to use a certain enum from it, rather than declaring it in the file where I need to use it. I do this because it makes things clean, I can access every enum in 1 place rather than having pages openned solely for accessing one enum.

Is this a bad practice and can it affect performance in any way?

答:
To me it all depends on the scope of your project. If there is one file with say 10 structs and that are the only ones ever used, I'd be perfectly comfortable having one .h file for it. If you have several different types of functionality, say a units, economy, buildings, etc I would definitely split things up. Create a units.h where all structs that deal with units reside. If you want to do something with units somewhere you need to include units.h sure, but it also is a nice "identifier" that something with units is probably done in this file.

Look at it this way, you don't buy a supermarket because you need a can of coke ;)


答:
Well, this is just data (not behaviour). The worst that could possibly/theoretically happen is that the same code is included and compiled more than once producing a relatively larger program.

It is just plain impossible that such includes can add more cycles to your operations, given that there isn't any behavioural/procedural code inside them (no loops, no ifs, etc.).

A (relatively) larger program can hardly affect performances (speed of execution) and, in any case, is just a remote theoretical concern. Most (maybe all) compilers manage includes in a way that prevent such problems.

IMHO, the advantages that you get with a single file (more readable and more manageable code) largely exceed any possible drawback.

Title: Is it a bad practice to include all the enums in one file and use it in multiple classes?

Body:
I'm an aspiring game developer, I work on occasional indie games, and for a while I've been doing something which seemed like a bad practice at first, but I really want to get an answer from some experienced programmers here.

Let's say I have a file called enumList.h where I declare all the enums I want to use in my game:

```<code>// enumList.h

enum materials_t { WOOD, STONE, ETC };
enum entity_t { PLAYER, MONSTER };
enum map_t { 2D, 3D };
// and so on.

// Tile.h
#include "enumList.h"
#include <vector>

class tile
{
    // stuff
};
</code>```

The main idea is that I declare all enums in the game in 1 file, and then import that file when I need to use a certain enum from it, rather than declaring it in the file where I need to use it. I do this because it makes things clean, I can access every enum in 1 place rather than having pages openned solely for accessing one enum.

Is this a bad practice and can it affect performance in any way?


问:
add a prefix to localhost
Is there any possibility to add a prefix before localhost?

My question is that I want to add a prefix before localhost for my project url (ie. "dev.localhost/project/default.htm"). This is for an ASP.NET application running in IIS.

答:
Yes, this is possible, depending on the webserver you use.

For Apache you can create a virtual host config.

You can do it like this:

```<code>NameVirtualHost 127.0.0.1

<VirtualHost 127.0.0.1>
   DocumentRoot "C:\project1"
   ServerName dev1.localhost
</VirtualHost>

<VirtualHost 127.0.0.1>
   DocumentRoot "C:\project2"
   ServerName dev2.localhost
</VirtualHost>
</code>```

See also: http://www.apptools.com/phptools/virtualhost.php

Further, you'll hav to put an entry in your hosts file to redirect to 127.0.0.1.

```<code>127.0.0.1 dev1.localhost
127.0.0.1 dev2.localhost
</code>```

Title: add a prefix to localhost

Body:
Yes, this is possible, depending on the webserver you use.

For Apache you can create a virtual host config.

You can do it like this:

NameVirtualHost 127.0.0.1

<VirtualHost 127.0.0.1>
   DocumentRoot "C:\project1"
   ServerName dev1.localhost
</VirtualHost>

<VirtualHost 127.0.0.1>
   DocumentRoot "C:\project2"
   ServerName dev2.localhost
</VirtualHost>

See also: http://www.apptools.com/phptools/virtualhost.php

Further, you'll hav to put an entry in your hosts file to redirect to 127.0.0.1.

127.0.0.1 dev1.localhost
127.0.0.1 dev2.localhost


答:
I'm sorry, but the short answer is no.  A URL has a specific defined format of:

```<code>[protocol]:[user@]host:[port]/[path]
</code>```

so in your example, the protocol is implied as HTTP, there is no username, the host is localhost, its using port 80, the default for HTTP, and the file path is /project/default.htm.  It makes more sense to use the path part to diferentiate the different project locations.

The longer answer, is yes, but this depends on how you are hosting your project URLs. The HTTP protocol identifies the host part of the URL when it makes the request to the server. Some Web servers then use this to serve multiple sites from the same computer. (think web hosting companies running multiple customer websites on a single server).  This means you could create multiple hostnames for your computer, and then configure the webserver to reference different projects based on the hostname used to connect to.  not sure that dev.localhost is a good idea, dev-localhost may well work better, with an entry in /etc/hosts to identify its ip address as 127.0.0.1

Title: add a prefix to localhost

Body:
Is there any possibility to add a prefix before localhost?

My question is that I want to add a prefix before localhost for my project url (ie. "dev.localhost/project/default.htm"). This is for an ASP.NET application running in IIS.

Body:
I'm sorry, but the short answer is no.  A URL has a specific defined format of:

[protocol]:[user@]host:[port]/[path]

so in your example, the protocol is implied as HTTP, there is no username, the host is localhost, its using port 80, the default for HTTP, and the file path is /project/default.htm.  It makes more sense to use the path part to diferentiate the different project locations.

The longer answer, is yes, but this depends on how you are hosting your project URLs. The HTTP protocol identifies the host part of the URL when it makes the request to the server. Some Web servers then use this to serve multiple sites from the same computer. (think web hosting companies running multiple customer websites on a single server).  This means you could create multiple hostnames for your computer, and then configure the webserver to reference different projects based on the hostname used to connect to.  not sure that dev.localhost is a good idea, dev-localhost may well work better, with an entry in /etc/hosts to identify its ip address as 127.0.0.1


答:
I really think it is a bad practice. When we measure code quality, there's something we call "granularity". Your granularity suffers severely by putting all those enums in one single file and thus maintainability suffers, too.

I'd have a single file per enum to find it quickly and group it with the behavioural code of the specific functionality (e.g. materials enum in folder where material behaviour is etc.);

The main idea is that I declare all enums in the game in 1 file, and
  then import that file when I need to use a certain enum from it,
  rather than declaring it in the file where I need to use it. I do this
  because it makes things clean, I can access every enum in 1 place
  rather than having pages openned solely for accessing one enum.

You might think it is clean, but in fact, it is not. It's coupling things that do not belong together functionality- and module-wise and decreases the modularity of your application. Depending on the size of your code base and how modular you want your code to be structured, this might evolve into a bigger problem and unclean code/dependencies in other parts of your system. However, if you just write a small, monolithic system, this does not necessarily apply. Yet, I would not do it like this even for a small monolithic system.


问:
Opinions on logging in multiprocess applications
We have written an application that spawns at least 9 parallel processes. All processes generate a lot of logging information.

Currently we are using Python’s QueueHandler to consolidate all logs into one file. Unfortunately, this sometimes results in very messy files which are hard to read (making it difficult to track exactly what’s going on in one thread).

Do you think it is a viable option to separate all messages into dedicated files? Or will this make things even messier, due to the high number of files?

What are your general experiences when writing log files for multiprocessed/multithreaded applications?

答: It really depends on your application, and how you analyse the logs.  Consider the high end server extreme case where you have many threads all interacting. Consoldating this at log time into a single queue, and writing into a file in time order allows you to determine fairly precisely the order events occured in is one solution, but a better solution would be to have multiple logs, have each log event record the tick time, and then use splunk to perform the analysis.</p>


问:
How to get initial API right using TDD?
This might be a rather silly question as I am at my first attempts at TDD. I loved the sense of confidence it brings and generally better structure of my code but when I started to apply it on something bigger than one-class toy examples, I ran into difficulties.

Suppose, you are writing a library of sorts. You know what it has to do, you know a general way of how it is supposed to be implemented (architecture wise), but you keep "discovering" that you need to make changes to your public API as you code. Perhaps you need to transform this private method into strategy pattern (and now need to pass a mocked strategy in your tests), perhaps you misplaced a responsibility here and there and split an existing class.

When you are improving upon existing code, TDD seems a really good fit, but when you are writing everything from scratch, the API you write tests for is a bit "blurry" unless you do a big design up front. What do you do when you already have 30 tests on the method that had its signature (and for that part, behavior) changed? That is a lot of tests to change once they add up.

答:
As Robert Harvey just said, you are probably trying to use TDD for something that should be handled by a different conceptual tool (that is: "design" or "modelling").

Try to design (or "model") you system in a quite abstract ("general", "vague") way. For example, if you have to model a car, just have a car class with some vague method and field, like startEngine() and int seats. That is: describe what you want to expose to the public, not how you want to implement it. Try to expose just basic functionalities (read, write, start, stop, etc) and leave the client code elaborate on it (prepareMyScene(), killTheEnemy(), etc).

Write down your tests assuming this simple public interface.

Change the internal behaviour of your classes and methods whenever you need it.

If and when you need to change your public interface and your test suite, stop and think. Most likely this is a sign that there is something wrong in your API and in your design/modelling.

It is not unusual to change an API. Most systems at their 1.0 version explicitly warn the programmers/users against possible changes in their API. Despite this, a continuous, uncontrolled flow of API changes is a clear sign of bad (or totally missing) design.

BTW: You should usually just have a handful of tests per method. A method, by definition, should implement a clearly defined "action" on some kind of data. In a perfect world, this should be a single action that corresponds to a single test. In the real world it is not unusual (and not wrong) to have few different "versions" of the same action and few different corresponding tests. For sure, you should avoid to have 30 tests on the same method. This is a clear sign that the method tries to do too much (and its internal code is grown out of control).

Title: How to get initial API right using TDD?


答:
Yes, it's bad practice, not because of performance but because of maintainability.

It makes things "clean" only in the OCD "collect similar things together" way. But that's actually not the useful and good kind of "cleanliness".

Code entities should be grouped to maximize cohesion and minimize coupling, which is best achieved by grouping them into largely independant functional modules. Grouping them by technical criteria (such as putting all enums together) achieves the opposite - it couples code that has absolutely no functional relatioship and puts enums that might be used only in one place into a different file.


问:
How to write efficient code despite heavy deadlines
I am working in an environment wherein we have many projects with strict deadlines on deliverables. We even talk directly to the clients so getting the jobs done and fast is a must.

My issue is that i'd always write code for the first solution that comes to my mind, which of course I thought as best at that moment. It always ends up ugly though and i'd later realize that there are better ways to do it but can't afford to change due to time restrictions.

Are there any tips by which I could make my code efficient yet deliver on time?

答:
I am a .Net developer working on web applications.

The things I have started to do is -

If it is C# code, I try to write that code in LinqPad first (if possible).

If it is Javascript code, I first write that code and test it in jsfiddle/jsbin (if possible).

I found that this helps with the quality of code but does not slow me down (and in several cases, I found it to be faster).

ContentLicense: CC BY-SA 2.5


问:
Why is heap size fixed on JVMs?
Can anyone explain to me why JVMs (I didn't check too many, but I've never seen one that didn't do it that way) need to run on a fixed heap size? I know it's easier to implement on a simple contiguous heap, but the Sun JVM is now over a decade old, so I'd expect them to have had time to improve this.

Needing to define the maximum memory size of your program at startup time seems such a 1960s thing to do, and then there are the bad interactions with OS virtual memory management (GC retrieving swapped out data, inability to determine how much memory the Java process is really using from the OS side, huge amounts of VM space wasted (I know, you don't care on your fancy 48bit machines...)). I also guess that the various sad attempts to build small operating systems inside the JVM (EE application servers, OSGi) are at least partially to blame on this circumstance, because running multiple Java processes on a system invariably leads to wasted resources because you have to give each of them the memory it might have to use at peak.

Surprisingly, Google didn't yield the storms of outrage over this that I would expect, but they may just have been buried under the millions of people finding out about fixed heap size and just accepting it for a fact.

答:
You need to give the GC some mechanism to tell it when to run, or your program will fill up the entire virtual memory space. There are many alternative ways to trigger GC: elapsed time, number of allocations, number of assignments, probably others that I can't think of right now. IMO none of those are as good as simply setting a memory boundary, and running GC when the allocated space hits that boundary.

The key is to set the correct boundaries. I look at -ms as "this is how much memory my app needs," and -mx as "it should never exceed this amount." In a production deployment, the two should be close if not equal, and they should be based on actual, measured requirements.

Your concerns about "wasted" virtual memory are misplaced: it's virtual, it's (almost) free. Yes, giving the heap too big an allotment means that you can't start as many threads, or load as many memory-mapped files. But that's part of application design: you have scarce resources, you need to partition them in a way that allows your application to run. In a "C-style" heap, which will expand until you hit the top of memory, the basic issue is the same, you just don't have to think about it until you're in trouble.

The only thing that a large heap might "waste" is swap space, because all writable segments require a commitment from swap. But that is part of system design: if you want to have lots of JVMs running on the same box, either increase your swap or decrease their heap allotment. If they start thrashing, then you're trying to do too much with the system; buy more memory (and if you're still running a 32-bit processor, buy a new box).

Title: Why is heap size fixed on JVMs?


问:
Design backward and forward button operations of a browser
If you were asked to design the backward and forward button operation (as a library) in a browser, how would you do it? What will be your APIs and parameters to them? what data structure will be best suitable for this usecase?</p>

答:
Simplest solution would be to use two stacks (back, forward).

Clicking the back button will pop from the back stack and push the current page on the forward stack (and go to the popped value on the back stack).

Clicking on any link on a page (following a link) will clear the forward stack and push the current page on the back stack.

Clicking on the forward button will pop from the forward stack and push the current page on the back stack (and go to the popped value on the forward stack).

The back and forward buttons are disabled when the appropriate stack is empty.


答:
I would use an array containing urls, with a variable storing the length and an index pointing to the current item being displayed.

Back decrements the index, Forward increments the index. New page increments the index, stores the url at that place in the array and sets the length to the index value.

When the array is full, I would either use a realloc() for requesting more memory or implement a ring access to the array, depending on the memory constraints.

Title: Design backward and forward button operations of a browser

Body: If you were asked to design the backward and forward button operation (as a library) in a browser, how would you do it? What will be your APIs and parameters to them? what data structure will be best suitable for this usecase?</p>


问:
Using 'new' in a projection?
I wish to project a collection from one type (Something) to another type (SomethingElse).  Yes, this is a very open-eneded question, but which of the two options below do you prefer?

Creating a new instance using new:

```<code>var result = query.Select(something => new SomethingElse(something));
</code>```

Using a factory:

```<code>var result = query.Select(something => SomethingElse.FromSomething(something));
</code>```

When I think of a projection, I generally think of it as a conversion.  Using new gives me this idea that I'm creating new objects during a conversion, which doesn't feel right.  Semantically, SomethingElse.FromSomething() most definitely fits better.  Although, the second option does require addition code to setup a factory, which could become unnecessarily compulsive.

答:
This question appears to be more about the appropriateness of using a factory method over a straight constructor call. My favorite example uses the TimeSpan type because it has several constructor overloads and several FromXXX static factory methods.

```<code>// how easily can you spot the bug?
int[] durationMs = { 1, 2, 3, 4 };

IEnumerable<TimeSpan> durations1 =
    durationMs.Select(ms => new TimeSpan(0, 0, ms));

IEnumerable<TimeSpan> durations2 =
    durationMs.Select(ms => TimeSpan.FromSeconds(ms));
</code>```

Which expression was the bug easier to spot in the two equivalent projections? Fixing the two expressions is also interesting:

```<code>// spot the bug after the fix?
IEnumerable<TimeSpan> durations1 =
    durationMs.Select(ms => new TimeSpan(0, 0, 0, ms));

IEnumerable<TimeSpan> durations2 =
    durationMs.Select(ms => TimeSpan.FromMilliseconds(ms));
</code>```

The durations2 expression is correct (bug fixed). However, adding just one 0 parameter to the durations1 constructor call was not enough - we have to add another 0 - going from the 3 parameter version to the 5 parameter version in order to specify milliseconds (as documented on msdn).

The "Framework Design Guidelines" book has some great advice on when to provide static factory methods. The book goes into more detail on each point whereas the link I provided merely summarizes the advice. Hope this helps.

Title: Using 'new' in a projection?

Body:
This question appears to be more about the appropriateness of using a factory method over a straight constructor call. My favorite example uses the TimeSpan type because it has several constructor overloads and several FromXXX static factory methods.

// how easily can you spot the bug?
int[] durationMs = { 1, 2, 3, 4 };

IEnumerable<TimeSpan> durations1 =
    durationMs.Select(ms => new TimeSpan(0, 0, ms));

IEnumerable<TimeSpan> durations2 =
    durationMs.Select(ms => TimeSpan.FromSeconds(ms));

Which expression was the bug easier to spot in the two equivalent projections? Fixing the two expressions is also interesting:

// spot the bug after the fix?
IEnumerable<TimeSpan> durations1 =
    durationMs.Select(ms => new TimeSpan(0, 0, 0, ms));

IEnumerable<TimeSpan> durations2 =
    durationMs.Select(ms => TimeSpan.FromMilliseconds(ms));

The durations2 expression is correct (bug fixed). However, adding just one 0 parameter to the durations1 constructor call was not enough - we have to add another 0 - going from the 3 parameter version to the 5 parameter version in order to specify milliseconds (as documented on msdn).

The "Framework Design Guidelines" book has some great advice on when to provide static factory methods. The book goes into more detail on each point whereas the link I provided merely summarizes the advice. Hope this helps.


问:
How to evaluate code quality when you're not familiar with the language?
As a hypothetical, if I were to interview someone for a new PHP developer position when my experience is in .NET, how can I determine if the code sample they've provided me is efficient and of good quality?

In other words, what is the best way to evaluate a programmer's code if you're not familiar with the language?

答:
Regardless of language:

Are there clear separations of concerns, appropriate use of classes
(for OO languages), or any indications of deliberate attempts to break
down the code into reusable, modular 'chunks'?

Similarly, any evidence of testing - unit testing or otherwise?

If it's production code, is it strewn with debug strings that might suggest little separation between development and deployment?

Does the code follow any kind of naming convention (whether you like that convention or not is immaterial!)?

If you have the file, rather than a printout, does every function/class in the file relate to the (so if it's a file called data_access_layer, evidence of functions that process images would probably be out of place).

Any indications of a lack of trust for user input are good too, especially for web-based languages like PHP. So structures like input = escape(input) at least show you that they're aware of the issue.

Comments or self-describing code is always good. There are several schools of thought on the amount of commenting that should be present, but a complete absence of comments

At the cost of being cynical, I would also google some of the code before the interview. It could easily be a copy and paste job, sadly.

Not saying that any code that doesn't have all of these is automatically poor, but I'd consider these to be indicators of someone who has reflected on and considered their practice.

However, for all of these indicators, you should ask what the rationale for the code being like that is. There may be a good, language-specific reason for their choices...and after that, google is your friend when they and the other candidates go away, as you can check whether what they said sounds plausible...!

Good luck, as hiring good people is one of the most important roles in your organisation ;)


问:
Why is using C++ libraries so complicated?
First of all, I want to note I love C++ and I'm one of those people who thinks it is easier to code in C++ than Java. Except for one tiny thing: libraries.

In Java you can simply add some jar to the build path and you're done.

In C++ you usually have to set multiple paths for the header files and the library itself. In some cases, you even have to use special build flags. I have mainly used Visual Studio, Code Blocks and no IDE at all. All 3 options do not differ much when talking about using external libraries.

I wonder why was there made no simpler alternative for this? Like having a special .zip file that has everything you need in one place so the IDE can do all the work for you setting up the build flags. Is there any technical barrier for this?

答: C++ was designed to improve the C language by making an easier, more automated language with support for object oriented programming.  But it didn't do anything to change or improve the way C handles external libraries and header files.    C++ has no module system like more modern languages - it still uses the C preprocessor and linker system.  Since one of the stated goals of C++ was backwards compatibility with C code, this isn't really surprising.  Any C++ module system would have to work alongside the old C header-file/linker system.  The C++ standards committee simply hasn't gotten around to designing a more modern module system.  (Although they are working on it, see Klaim's comment below.)</p>


问:
How to learn Cloud Computing and Big Data at home?
I want to learn Cloud Computing and Big Data at home.

Is it possible to learn these technologies on home PC?

Which technologies to learn in Cloud Computing?

Which technologies to learn Big Data (Hadoop)?

答:
Since you are a .NET guy, you can go with the Windows Azure. You can start building applications at your home PC itself using the tools which you are familiar with (Visual Studio etc). For deploying in Windows Azure, you will be coding your app, running it locally and if everything working fine, you can push that to cloud.

Windows Azure has some subscriptions where you will get some free benefits. Check the Windows Azure 90 day free trial. Also, if you have an MSDN subscription, you can get free Azure benefits. An MSDN Visual Studio Ultimate subscriber is entitled to up to 3700$ worth of Azure benefits every month.

If you are looking for a basic cloud computing course, you may consider EXIN Cloud Computing foundation certification course as well.

BigData:

Here is a great FREE resource to start with BigData: http://bigdatauniversity.com/

Note:  If you would like to learn more about cloud computing/ BigData etc, register at GetCloudCertified.com (URL given below). We will be launching our website by early 2013. Feel free to follow us on Twitter and FB for the time being for more details.

Cheers!
GetCloud
http://getcloudcertified.com


问:
Setting up ASP.NET structure for code
I've always coded in C# MVC3 when developing web applications. But now i wanted to learn a bit more about developing web sites with just ASP.NET.

But now i'm wondering what a good setup for my code would be. For me, an MVC like pattern seems to be a good way to go. But obviously ASP.NET doesn't have any router and controller classes. So i guess people have a different way of setting up their code when they do ASP.NET.

So i'm looking for more information on how to get started with this. So not really the basics of ASP.NET, but something that focuses on a good code setup.

Any good tutorials/information about this/?

答:
MVC3 is ASP.NET in every sense. It seems like you are referring to WebForms, which is the old platform for creating websites in ASP.NET. But I think you'll find MVC to be a much better platform.

As mention by Alex, MVC offers a better separation of concerns by following the Model-View-Controller pattern, which can be implemented in WebForms, but has native support in MVC. It also offers better HTML code generation using the Razor engine, which I find pretty smart in most cases and very clean, simple code. Better file structure, and other features to keep the development on the actual site rather than handling requests back and forth IMHO.

Title: Setting up ASP.NET structure for code


问:
How to add a new developer to the team
I run a small company composed of only 2 developers. We are building a very big application for one of our clients. Development on this project has gone on for 1.5 years.

Now this client has secured an important sponsorship, and they are organizing events related to this project. So now we have a deadline in 2 months and we can't miss it.

We are thinking of adding a new developer to the team, and I am wondering what we can do to help his integration.

This is the situation:

We are approaching the threshold of Brooks's law -- the point when adding new developers will be counter-productive.

The application is relatively well-designed, but the implementation is chaotic in some points (especially older code).

There are unit tests only for more recent code. When this project started, we didn't regularly conduct tests.

Documentation and comments are incomplete.

The application is both large and complex.

The client has written down almost every detail about his project, in a very clear and "programmer-friendly" way.

Is it a good idea to add a person now? If so, what can we do in order to help the new developer integrate into the team?

EDIT:

The sponsor is organizing an internet-based sport event for next spring. It must start on a specific day of the year. We can't change it.

What we developers (I am one of the two) need to do is:

Completing the existing application (about 25% of the work to do).

Creating a new module, essential for the organization of this event (about 75% of the work to do). This new module can't be developed without understanding the main program's API.

I can't do an exact time estimation, but we are in a risky situation.

答:
If you strictly follow Brook's Law, you will likely never grow your team.

The trick is to bring on the new person without getting hit with too much slowdown on your current team.  Eventually the new person will be up to speed, and you can get over the hump.

In your case? I would recommend have the new person write all those missing unit tests.

Those are sorely needed as a safeguard against regression errors,
which will burn you faster than any Brooks slowdown.

New person will learn the guts of your system.  It's a bit of a
trial by fire--but their output is not going into production code,
so little risk there.

Place a hard limit on how much of the other team members time they
can take.  E.g., have them queue up questions, and only allow 30
minutes a day interacting with other team members until the deadline
is met.

Also, let's face it: you will have to manage scope, and client expectations regardless of whether you bring on a new person or not.  The payoff comes next cycle.

Ed Yourdon had a great comment about Brook's Law. He said: of course, adding people will make you go slower--but when a project is at risk is the only time management will bring on new people.  So: take them, minimize the impact to the current release, and get rid of poor performers as soon as you can.  This way, over time, you can build a strong team.

Title: How to add a new developer to the team


答:
It's not a technical barrier.  On Linux, your "special zip file" is a library-dev package you install with a package manager, and setting up the include and linker flags is as simple as adding a couple lines to your configure.ac that uses pkg-config to set things up.

Pkg-config is available for Windows too, but cultural barriers have prevented its widespread adoption.  Unix has a strong history of enabling portability by distributing source code, so they include the development tools for free.  Windows has a strong history of encouraging only binary distribution and charging developers for tools.  When you make your money selling libraries, it doesn't make sense to make it easier for third parties to provide them.

Title: Why is using C++ libraries so complicated?

Body:
First of all, I want to note I love C++ and I'm one of those people who thinks it is easier to code in C++ than Java. Except for one tiny thing: libraries.

In Java you can simply add some jar to the build path and you're done.

In C++ you usually have to set multiple paths for the header files and the library itself. In some cases, you even have to use special build flags. I have mainly used Visual Studio, Code Blocks and no IDE at all. All 3 options do not differ much when talking about using external libraries.

I wonder why was there made no simpler alternative for this? Like having a special .zip file that has everything you need in one place so the IDE can do all the work for you setting up the build flags. Is there any technical barrier for this?


问:
OOP Design: relationship between entity classes
I have at first sight a simple issue but can't wrap my head around on how to solve. I have an abstract class Compound. A Compound is made up of Structures. Then there is also a Container which holds 1 Compound.

A "special" implementation of Compound has Versions. For that type of Compound I want the Container to hold the Versionof the Compound and not the Compound itself.

You could say "just create an interface Containable" and a Container holds 1 Containable. However that won't work. The reason is I'm creating a framework and the main part of that framework is to simplify storing and especially searching for special data type held by Structure objects. Hence to search for Containers which contain a Compound made up of a specific Structure requires that the "Path" from Containerto Structure is well defined (Number of relationships or joins).

I hope this was understandable. My question is how to design the classes and relationships to be able to do what I outlined.

EDIT:

Kind of translation issue. with version i did not mean in terms of "versioning" but more in terms of "different variety" but fundamentally the same. There is no active / inactive. All are active.

EDIT 2:

Also note that these classes are entity classes and hence complex inheritance and hierarchies can be problematic.

EDIT 3:

Just don't see how either pattern (Composite, decorator) can work. I tried but the problem is the "path traversal", eg. implementing it in the context of Spring-data and QueryDSL.

I've created Class diagramm with comments that might help to understand the issue. Batch = Version.

答:
There are so many ways to accomplish variation in code structures and function.

In this case, if their are no functions that operate differently for a versioned Compound than   a non-versioned Compound, then inheritance or some design pattern would be overkill.

How about just an attribute "version"?  For simple compounds, the version could be "none" or 0 or 1, whatever makes most sense for the way you use it.

If for some reason the actual functions on Compound need to be implemented differently, then you do want polymorphism. In that case, I think neontapirs description of using the Composite pattern is a good direction.

How do you expect the client code to use a Compound versus a Versioned Compound?

Are these like isotopes, or left-handed/right-handed sugars?


问:
What constitutes a programming language and how does one copyright a programming language?
I've decided to create a programming language of my own, mostly just for fun. However, I got interested in the legal aspect of it all.

You can, for example, licence specific programs under specific terms. However, how do you go about licensing a language? Also, by that I don't just mean the implementation of the language (compiler & VM), but the standard itself. Is there something else to a programming language I'm missing?

What I would like to achieve by such licensing:

Make it completely FOSS (can a language even be FOSS, or is that the implementation that can be FOSS?)

Establish myself as the author (can you legally be an author of a language? Or, again, just the implementation?)

Make it so that anyone implementing my language would be required to attribute me (MIT-style. Please note that I do not have any hopes for anyone actually ever doing that though, I'm just learning.)

I think that the solution would be to separately license the VM and the compiler for my language, as "the official implementation", and then license the design document as the language itself.

What exactly am I missing here?

答:
Disclaimer.IANAL();

You can't copyright a programming language no more than you can copyright a spoken language. You can license a particular implementation of the language and even sell that compiler much how Borland did with Delphi for many years.

Many languages today have a BDFL (Benevolent Dictator for Life) who determines what goes into the language and what doesn't. Python, Ruby, and Perl are all examples of that.

Other languages have officially designed standards by one of several standards boards, typically ANSI, ECMA, or ISO. Examples include C, C++, and Javascript.

Some languages fall into murkier areas due to politicking between companies. Java is an example because Microsoft sits on some of the standards boards.

Some languages move from one to another, typically from BDFL to Standardized, C is a good example.

Depending on the specification of the language, some compiler writers may implement different features in different ways (CPython vs PyPy for example) or add features (Microsoft C++ vs GNU C++ or MySQL vs PostGreSQL vs SQL Server)


答:
You could write a grammar for your language and assert your copyright over that. Of course, that wouldn't protect you against someone writing a different grammar that described the same language.

My biggest question would be "why would you want to". After all, you probably want people to adopt your language. If someone else claimed to have created it, then simply having a good web presence would be enough to enable you to call them a liar.

As others have noted, if your main goal is to prevent others from stealing the name of your language, a trademark would be more useful.

Title: What constitutes a programming language and how does one copyright a programming language?

Body:
I've decided to create a programming language of my own, mostly just for fun. However, I got interested in the legal aspect of it all.

You can, for example, licence specific programs under specific terms. However, how do you go about licensing a language? Also, by that I don't just mean the implementation of the language (compiler & VM), but the standard itself. Is there something else to a programming language I'm missing?

What I would like to achieve by such licensing:

Make it completely FOSS (can a language even be FOSS, or is that the implementation that can be FOSS?)

Establish myself as the author (can you legally be an author of a language? Or, again, just the implementation?)

Make it so that anyone implementing my language would be required to attribute me (MIT-style. Please note that I do not have any hopes for anyone actually ever doing that though, I'm just learning.)

I think that the solution would be to separately license the VM and the compiler for my language, as "the official implementation", and then license the design document as the language itself.

What exactly am I missing here?


问:
how do early stage startups hire ninja programmers
I am programmer who just started working on a startup idea. At the moment I want to bring onboard at least one programmer. This programmer should be a ninja - a 10x engineer.

Since early days are probably the most risky for a startup, I want to make sure I approach this problem the best I can.

How do I find these people? and How do I convince them to come onboard?

I would love to hear from people who started their own companies and what their thoughts are about hiring

Update: I would like to get the ninja as a co-founder so besides being a ninja (ie. great programmer with computer science background) he/she has to have a healthy appetite for risk (for great programmers this is not a big deal because they can be hired anytime into mainstream jobs if the startup doesn't work)

答:
Your update "I would like to get the ninja as a co-founder..." tells me loud and clear you WON'T be paying ninja money. You're hoping to bring in somebody to make your vision turn out without compensating them, and instead promising them heaps of riches at some future time.

As somebody who's heard that tune before: good luck with that.


问:
Help parsing long (3.5mil lines) text file, line by line and storing data, need a strategy
This is a question about solving a particular problem I am struggling with, I am parsing a long list of text data, line by line for a business app in PHP (cron script on the CLI).  The file follows the format:

```<code>    HD: Some text here {text here too}

    DC: A description here
    DC: the description continues here
    DC: and it ends here.

    DT: 2012-08-01

    HD: Next header here {supplemental text}

    ... this repeats over and over for a few hundred megs
</code>```

I have to read each line, parse out the HD: line and grab the text on this line.  I then compare this text against data stored in a database.  When a match is found, I want to then record the following DC: lines that succeed the matched HD:.

Pseudo code:

```<code>    while ( the_file_pointer_isnt_end_of_file) {
        line = getCurrentLineFromFile
        title = parseTitleFrom(line)
        matched = searchForMatchInDB(line)
        if ( matched ) {
            recordTheDCLines  // <- Best way to do this?
        }
    }
</code>```

My problem is that because I am reading line by line, what is the best way to trigger the script to start saving DC lines, and then when they are finished save them to the database?

I have a vague idea, but have yet to properly implement it.  I would love to hear the communities ideas\suggestions!

Thank you.

答:
Write a two functions or a class LineReader with the following functions:

string GetNextLine() : reads next line from file

string PeekLine() : gets the next line from file, but don't move the file pointer

(you can implement this easily by a line buffer consisting of a string variable holding one line in advance; GetNextLine has to make use of that buffer as well as PeekLine).

Then, the implementation of recordDCLines should be something like

```<code> while(substr(PeekLine(),0,3)=="DC:")
 {
    line=GetNextLine();
    // process line, append it to a buffer
 }
 // here, store the found DC block
</code>```

EDIT: some pseudo code, I am not experienced in PHP, but I hope you get the general idea:

```<code> void OpenFile()
 {
     // do stuff here to open file
     // ...
     $nextline = getNextLineFromFile();
     $endoffile = false;
 }

 string GetNextLine()
 {
      if(isset($nextline))
      {
         $result=$nextline;
         if(!noMoreLinesAvailable())
             $nextline = getNextLineFromFile();
         else
             unset($nextline);
      }
      else
      {
         $endoffile=true;
         $result ="";
      }
      return $result;
 }

 string PeekLine()
 {
     return $nextline;
 }
</code>```

Body:
Write a two functions or a class LineReader with the following functions:

string GetNextLine() : reads next line from file

string PeekLine() : gets the next line from file, but don't move the file pointer

(you can implement this easily by a line buffer consisting of a string variable holding one line in advance; GetNextLine has to make use of that buffer as well as PeekLine).

Then, the implementation of recordDCLines should be something like

 while(substr(PeekLine(),0,3)=="DC:")
 {
    line=GetNextLine();
    // process line, append it to a buffer
 }
 // here, store the found DC block

EDIT: some pseudo code, I am not experienced in PHP, but I hope you get the general idea:

 void OpenFile()
 {
     // do stuff here to open file
     // ...
     $nextline = getNextLineFromFile();
     $endoffile = false;
 }

 string GetNextLine()
 {
      if(isset($nextline))
      {
         $result=$nextline;
         if(!noMoreLinesAvailable())
             $nextline = getNextLineFromFile();
         else
             unset($nextline);
      }
      else
      {
         $endoffile=true;
         $result ="";
      }
      return $result;
 }

 string PeekLine()
 {
     return $nextline;
 }


答:
You could consider writing a PHP extension in C or C++ for that purpose; you could then use low-level, but efficient syscalls (e.g. mmap(2), read(2) into a large buffer, readahead(2), etc...)

You could also delegate to a helper program written in C.

Title: Help parsing long (3.5mil lines) text file, line by line and storing data, need a strategy

Body:
This is a question about solving a particular problem I am struggling with, I am parsing a long list of text data, line by line for a business app in PHP (cron script on the CLI).  The file follows the format:

```<code>    HD: Some text here {text here too}

    DC: A description here
    DC: the description continues here
    DC: and it ends here.

    DT: 2012-08-01

    HD: Next header here {supplemental text}

    ... this repeats over and over for a few hundred megs
</code>```

I have to read each line, parse out the HD: line and grab the text on this line.  I then compare this text against data stored in a database.  When a match is found, I want to then record the following DC: lines that succeed the matched HD:.

Pseudo code:

```<code>    while ( the_file_pointer_isnt_end_of_file) {
        line = getCurrentLineFromFile
        title = parseTitleFrom(line)
        matched = searchForMatchInDB(line)
        if ( matched ) {
            recordTheDCLines  // <- Best way to do this?
        }
    }
</code>```

My problem is that because I am reading line by line, what is the best way to trigger the script to start saving DC lines, and then when they are finished save them to the database?

I have a vague idea, but have yet to properly implement it.  I would love to hear the communities ideas\suggestions!

Thank you.


答: Separate the problem -- one script plows through and reads and stuffs the interesting stuff into some sort of data store. Second script pulls from the data store and processes the records. I suspect this will be much faster than doing it in the same script for no other reason than the 2nd script effectively multi-threads the app.</p>


问:
Can I (reasonably) refuse to sign an NDA for pro bono work?
A friend of mine (let's call him Joe) is working on a promising project, and has asked me for help. As a matter of friendship I agreed (orally) not to discuss the details, but now he has a potential investor who wants me to sign a non-disclosure agreement (NDA). Since thus far all my work has been pro bono I told Joe I am not comfortable putting myself under documented legal obligation without some kind of compensation for the risk. (It needn't be strictly financial. I would accept a small ownership stake or possibly even just guaranteed credits in the code and documentation.)

Is my request reasonable, or am I just introducing unnecessary complexity?

答:
Your never compelled to sign any sort of contract, and, if you do sign something when not of a sound mind, or under some sort of duress, then whatever you signed could (and should) be deemed as null and void.

Having said that, your request in my opinion is unreasonable. An NDA or NCNDA is about the most rudimentary piece of paper. You shouldn't be afraid of it, unless, of course you plan on disclosing information that the other party doesn't want you to disclose. At this point there is no guarantee of success in negotiation, only the terms and conditions prior to discussion.

If anything, since you aren't an employee, and not bound by the terms and conditions of an employment contact, its even MORE grounds for you to be requested to sign an NDA.

However, should your friend receive financial benefit as a clear result of your contribution, via the investor injecting funds, you should perhaps review things with your friend and steer things away from a 'Pro-Bono' type arrangement, in lieu of your professional services rendered.

ANAL - Am Not A Lawyer. ;-)


问:
How do people read big technical books?
I see that most of the good programmers have the habit of reading big books for learning about technology.

What does it really take to read technical books, apart from the real interest on the technology?

How can I improve my ability to read these books?

答: What I do is kinda "Breadth-first read": first the table of contents, then I try to read the chapters in order but not so in-depth, skipping big chunks of text and going straight to code, backtracking a little if necessary to understand it. Having a better idea of the book, I fully read the interesting chapters and left the rest of the book to be read "on demand".</p>

Title: How do people read big technical books?


答:
Get paid or Open Source the code

Any time a 'business interest' decides to establish legal restrictions I would absolutely make them pay for that privilege. A NDA is basically a gag order that prevents you from sharing internal information pertaining to their company/project. Basically, if you talk about information private to their company they have the right to sue.

It's insurance for them but if they decide to lock the code you wrote into a proprietary licensing scheme there's nothing you can do about it as talking about the internal details would be violating the NDA.

If you don't already have the code covered under a license, you could try to release it under a permissive license (ex MIT) that will guarantee your right to continue using the code you wrote in the future.

The only problem with retroactively applying a license to existing code is, every contributor needs to agree to the license terms as their individual contributions have an implicit copyright to the developer who wrote them.

Worst Case (they win, you lose):

Your friend jumps onboard, they use your code, and lock it down under a proprietary licensing scheme.

They can legally prevent you from using the code you wrote on future projects, unless you lawyer up and come up with sufficient proof that they are using your code without permission (ie violating your personal copyright).

Either way, if they go with a proprietary licensing scheme you should be compensated for your efforts.

Good Case (they lose, you win):

You setup terms for compensation for the code. Basically, they purchase rights to use the code you wrote without restrictions. At that point a NDA doesn't matter because you lose rights to build on the code anyway. Just don't share any of their internal information publicly or you put yourself at risk of being sued.

Best Case (win, win):

You release the project under a MIT license so anything written up until now is free for everybody to use and build on (including for commercial purposes). It guarantees that you can still build onto the code in the future regardless of what they use it for. A NDA still doesn't matter as long as you respect the terms. If they want to go in a proprietary direction, they're welcome to fork the main codebase.

There's a good chance that they're just trying to protect their interests. There's nothing wrong with that but be careful not to give them the legal right to screw you in the future if they choose to go down a path you don't agree with.

Even software that you write pro bono still isn't free until you setup a license that guarantees future usage. Sweat equity (ie effort) is always holds value and as long as it can be used to generate profits, there will always be somebody looking to gain ownership over the rights to use.

Some terms may depend on where your live too. Intellectual property rights are a messy business.

Disclaimer: IANAL (I Am Not A Lawyer).

Title: Can I (reasonably) refuse to sign an NDA for pro bono work?

Body:
A friend of mine (let's call him Joe) is working on a promising project, and has asked me for help. As a matter of friendship I agreed (orally) not to discuss the details, but now he has a potential investor who wants me to sign a non-disclosure agreement (NDA). Since thus far all my work has been pro bono I told Joe I am not comfortable putting myself under documented legal obligation without some kind of compensation for the risk. (It needn't be strictly financial. I would accept a small ownership stake or possibly even just guaranteed credits in the code and documentation.)

Is my request reasonable, or am I just introducing unnecessary complexity?


答:
Any attempt to restrict / control / own a language is doomed to failure. In order for a language to become widely used, people must feel a) that it solves a problem better than some existing, established language, and b)  they are comfortable that they won't suddenly be on the wrong end of a license / law suit. If they think that that is even possible, they will go elsewhere.

I offer the absolute Tragedy of Java, as performed by Larry Ellison (AKA Oracle) and Google. Ellison performed a global-scale legal faceplant that accomplished 2 things:

He showed the world that he would sue anyone he thought he could get money from, and

He guaranteed that future developments that were not absolutely already tied to Java would choose anything other than Java.

Google didn't just win this lawsuit, they eviscerated Oracle's pathetic claims of patent and copyright. After this, no one I know will place any faith whatsoever in any "open source technology" that has Oracle's fingerprints on it (think: MySQL).

If you want, you can skip the developer-centuries behind Java and go straight to being ignored ... just have all developer's sign a contract before they can use your new language.


问:
How can I give my client "full access" to their PHP application's MySQL database?
I am building a PHP application for a client and I'm seriously considering WordPress or a simple framework that will allow me to quickly build out features like forums, etc.

However, the client is adamant about having "full access" to the database and the ability to "mine the data."  Unfortunately, I'm almost certain they will be disappointed when they realize they won't be able to easily glean meaningful insight by looking at serialized fields in wp_usermeta, etc.

One thought I had was to replicate a variation on the live database where I flatten out all of those ambiguous and/or serialized fields into something that is then parsable by a mere mortal using a tool as simple as phpMyAdmin.

Unfortunately, the client is not going to settle for a simple backend dashboard where I create the custom reports for them even though I know that would be the easiest and most sane approach.

答: I would let them access PHPMyadmin, but put up a clause, that any data loss will not be my responsibility, as wordpress manages data differently like you said.</p>


答: Open the port the mysql server is listening on, and create for them a read-only user that they can connect to it with.

Title: How can I give my client "full access" to their PHP application's MySQL database?

Body:
I am building a PHP application for a client and I'm seriously considering WordPress or a simple framework that will allow me to quickly build out features like forums, etc.

However, the client is adamant about having "full access" to the database and the ability to "mine the data."  Unfortunately, I'm almost certain they will be disappointed when they realize they won't be able to easily glean meaningful insight by looking at serialized fields in wp_usermeta, etc.

One thought I had was to replicate a variation on the live database where I flatten out all of those ambiguous and/or serialized fields into something that is then parsable by a mere mortal using a tool as simple as phpMyAdmin.

Unfortunately, the client is not going to settle for a simple backend dashboard where I create the custom reports for them even though I know that would be the easiest and most sane approach.


答: Implement a basic state machine.  As you are reading lines, note the last 'command' (dc, dt, etc).  When you get a 'HD', do your lookups.  When you are in a DC state, you know to accumulate the message until the next item isnt a DC entry, at which point you do a write.  </p>


问:
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.

答: Java is just C++ with different classes.


答:
You say you need to complete 25% of the original work, plus new work. ANd you need to do this in two months - when it took you 18 months to do 75% of the work.   To be very blunt, this indicates to me that your estimation abilities are about average for a code-focused programmer - that is, you think things will take you about half to a third as long as they really do.

Heroics might allow you to deliver the product you've contracted for, but it won't be doing you or your customer any favors.  It will be shoddy and bug-ridden under these conditions, and you'll be running on fumes.

Keep in mind that time you spend hiring will also have a major impact on your availability - this isn't something you can just do in a weekend, it does take time to find talented employees that fit well. Expect to spend at least a couple of weeks searching, interviewing, etc.   Expect that you and your existing employee will lose about 10 hours a week of productive time while you search.

My recommendation:

Sit down with your customer, explain that you're in over your head, and work with him to reduce scope to bare minimum.

Edit Just saw the date here.  So how did it end up? (Thanks Ars Technica for posting a three-month-old question ;)

Title: How to add a new developer to the team

Body:
I run a small company composed of only 2 developers. We are building a very big application for one of our clients. Development on this project has gone on for 1.5 years.

Now this client has secured an important sponsorship, and they are organizing events related to this project. So now we have a deadline in 2 months and we can't miss it.

We are thinking of adding a new developer to the team, and I am wondering what we can do to help his integration.

This is the situation:

We are approaching the threshold of Brooks's law -- the point when adding new developers will be counter-productive.

The application is relatively well-designed, but the implementation is chaotic in some points (especially older code).

There are unit tests only for more recent code. When this project started, we didn't regularly conduct tests.

Documentation and comments are incomplete.

The application is both large and complex.

The client has written down almost every detail about his project, in a very clear and "programmer-friendly" way.

Is it a good idea to add a person now? If so, what can we do in order to help the new developer integrate into the team?

EDIT:

The sponsor is organizing an internet-based sport event for next spring. It must start on a specific day of the year. We can't change it.

What we developers (I am one of the two) need to do is:

Completing the existing application (about 25% of the work to do).

Creating a new module, essential for the organization of this event (about 75% of the work to do). This new module can't be developed without understanding the main program's API.

I can't do an exact time estimation, but we are in a risky situation.


答:
The Easy Way - as stated, just do it.  Move ahead using a tool you understand which is probably not the best tool for the job, get paid, and potentially leave them in a crappy situation.  This is how the majority of freelance web developers behave.

The Hard Way - take a step back and forget Wordpress.  If you actually want to provide good solutions for your clients, you'll need to actually listen to their needs.  Hopefully your skill set is wide enough that you can do this while still doing the actual work for them.  You've already recognized using a canned solution is going to behave how they want, but it doesn't meet all of their requirements.

Ask them why they need database access.  Most people will ask for things because they are nosey, not because it provides any actual business value to them.  If it does, then you're going to need to invest a lot more time and energy into a solution which may end up costing 10x more.  If they realize that, it'll either shut them up, give you much more interesting work, or they'll find somebody else to do it for them the easy way.  They still lose, but at least that loss isn't your fault anymore.

If you manage to keep them and continue with proper planning, then it really opens up the discussion. For instance... Do they need database access to interface with other applications? Open up an API instead.  Not only does this change your data model, but perhaps it adds complexity to your architecture as well.

As a few others have hinted at... always make sure you cover your ass as well.  If you give them data access, make sure you are each accountable for your actions independently.  Perhaps you hand off an application and they deal with the database.  You can easily prove they changed something from your latest release to them.  Or, you activate some sort of logging to track them.  Or better yet, you give them limited access so they can't screw anything up.


答: If you are thinking wordpress you might as well play to it's strong suit and use a backup plugin so your client can have a copy of the database on demand. Makes them happy and they really can't do any harm at the end of the day insofar as they can't easily pave over the app, just play with the data offline.</p>


问:
Should I use a parser generator or should I roll my own custom lexer and parser code?
What specific advantages and disadvantages of each way to working on a programming language grammar?

Why/When should I roll my own? Why/When should I use a generator?

答:
Rolling your own parser forces you to think directly about the complexity of your language.  If the language is hard to parse, it is probably going to be hard to understand.

There was a lot of interest in parser generators in the early days, motivated by highly-complicated (some would say "tortured") language syntax.  JOVIAL was a particularly-bad example: it required two symbol lookahead, at a time when everything else required at most one symbol.  This made generating the parser for a JOVIAL compiler more difficult than expected (as General Dynamics / Fort Worth Division learned the hard way when they procured JOVIAL compilers for the F-16 program).

Today, recursive descent is universally the preferred method, because it is easier for compiler writers.  Recursive descent compilers strongly reward simple, clean language design, in that it is a lot easier to write a recursive-descent parser for a simple, clean language than for a convoluted, messy one.

Finally:  Have you considered embedding your language in LISP, and letting a LISP interpreter do the heavy lifting for you?  AutoCAD did that, and found it made their life a lot easier.  There are quite a few lightweight LISP interpreters out there, some embeddable.


问:
OO Design, how to model Tonal Harmony?
I have started to write a program in C++ 11 that would analyse chords, scales, and harmony.
The biggest problem I am having in my design phase, is that the note 'C' is a note, a type of chord (Cmaj, Cmin, C7, etc), and a type of key (the key of Cmajor, Cminor). The same issue arises with intervals (minor 3rd, major 3rd).

I am using a base class, Token, that is the base class for all 'symbols' in the program. so for example:

```<code>class Token {
public:
    typedef shared_ptr<Token> pointer_type;
    Token() {}
    virtual ~Token() {}
};

class Command : public Token {
public:
    Command() {}
    pointer_type execute();
}

class Note : public Token;

class Triad : public Token; class MajorTriad : public Triad; // CMajorTriad, etc

class Key : public Token; class MinorKey : public Key; // Natural Minor, Harmonic minor,etc

class Scale : public Token;
</code>```

As you can see, to create all the derived classes (CMajorTriad, C, CMajorScale, CMajorKey, etc) would quickly become ridiculously complex including all the other notes, as well as enharmonics. multiple inheritance would not work, ie:

```<code>class C : public Note, Triad, Key, Scale
</code>```

class C, cannot be all of these things at the same time. It is contextual, also polymorphing with this will not work (how to determine which super methods to perform? calling every super class constructors should not happen here)

Are there any design ideas or suggestions that people have to offer? I have not been able to find anything on google in regards to modelling tonal harmony from an OO perspective. There are just far too many relationships between all the concepts here.

答:
Some generic advice.

If there is a lot of uncertainty expected in the class design (such as in your situation), I would recommend experimenting with different competing class designs.

Using C++ at this stage might be not as productive as other languages. (This issue is apparent in your code fragments having to deal with typedef and virtual destructors.) Even if the project goal is to produce C++ code, it might be productive to do initial class design in another language. (For example Java, though there are many choices.)

Do not choose C++ just because of multiple inheritance. Multiple inheritance has its uses but it is not the correct way to model this problem (music theory).

Take special attention to disambiguate. Even though ambiguities are abundant in English (textual) descriptions, these ambiguities must be resolved when designing OOP classes.

We speak of G and G sharp as notes. We speak of G major and G minor as scales. Thus, Note and Scale are not interchangeable concepts. There could not be any object that can be simultaneously an instance of a Note and a Scale.

This page contains a few diagrams that illustrate the relationship:
http://www.howmusicworks.org/600/ChordScale-Relations/Chord-and-Scale-Relations

For another example, "a Triad that starts with G on a C major scale" does not have the same meaning as "a Triad that starts with C on a G major scale".

At this early stage, the Token class (the superclass of everything) is unwarranted, because it prevents disambiguation. It could be introduced later if needed (supported by a code fragment that demonstrates how this could be useful.)

To begin with, start with a Note class which is the center of the class diagram, then gradually add the relationships (pieces of data that needs to be associated with tuples of Notes) to the class relationship diagram.

A C note is an instance of the Note class. A C note will return properties that are related to this note, such as related triads, and its relative position (Interval) with respect to a Scale that starts with a C note.

Relationships between instances of the same class (for example, between a C note and a E note) should be modeled as properties, not inheritance.

Moreover, many of the inter-class relationships in your examples are also more appropriately modeled as properties. Example:

(code examples are pending because I need to re-learn music theory...)

Title: OO Design, how to model Tonal Harmony?


问:
Separating merged array of arithmetic and geometric series
Given an array of positive integers in increasing order. Separate them in two series, an arithmetic sequence and geometric sequence. The given array is such that a solution do exist.

The union of numbers of the two sequence must be the given array.

Both series can have common elements i.e. series need not to be disjoint.

The ratio of the geometric series can be fractional.

Example:

```<code>Given series : 2,4,6,8,10,12,25
AP: 2,4,6,8,10,12
GP: 4,10,25
</code>```

I tried taking few examples but could not reach a general way. Even tried some graph implementation by introducing edges if they follow a particular sequence but could not reach solution.

答:
I would rather interpret your example as

AP: 2,4,6,8,10,12

GP: 25

as this is a valid interpretation as well and easier to find.

I'd first look at the first three integers. Let's call them a, b and c.

If b - a = c - b, you can assume that this is the step width of your arithmetic series, and the geometric series has not started yet.

If b/a = c/b, you can assume that this is the ratio of the geometric series, and that the arithmetic series has not started yet.

Independently of whether or not either of the above conditions are met (thanks to
tmyklebu for pointing this out), you have several other valid hypotheses. You can assume that any two of the numbers form the beginning of one of the series, and the remaining element the beginning of the other series.

You could maintain a list of currently valid hypotheses as you proceed along the array. In the case of a hypothesis with only a single started sequence, you have to assume that the first number not belonging to that sequence is the beginning of the other sequence. If you have one sequence and the start of another sequence, you will likely encounter a number which is not part of the defined sequence. You can use that to define the remaining sequence.

You have to take some care. When you had a geometric series and find the second number not fitting that series, you know you have found two numbers belonging to the arithmetic series. But their difference might be a multiple of the step width. So you should iterate over all divisors of that difference, and check whether the intermediate values indicated by thas reduced step width are present in the geometric series. Only up to two elements of an arithmetic series can be part of a geometric series as well, so no need to check all divisors. It is enough to check for half and one-third of the width, and only if that number is an integer. A similar consideration has to be used to find the ratio of the geometric series, taking posisble duplicate elements into account. You have to check for the square root and cubic root of the fraction of the two defining numbers, and see whether these are rational as well and result in integers. Rounding might be an issue unless you have a data structure to represent rational numbers and do prime factor decomposition.

It might be that multiple step widths or ratios are consistent with the data so far. In that case, you should go with all of them, checking the remaining data to see whether they still hold. In the end, you either have a single valid hypothesis, or a set of hypotheses from which you can choose at will. If you want to, you could then check whether any of these series can be extended before the assumed first element, by reusing elements of the other series. This could be used to find 4 and 10 in the example of yours. But the answer should be valid even without this step.

OwnerDisplayName: MvG


答:
You can try some method to find the longest arithmetic progression. Here is simple DP solution with quadratic complexity, and full pdf document contains clues to (theoretically) more effective method.

This method is applicable to geometric series to (checking A[i] + A[k] = 2*A[j] turns into A[i] * A[k] = A[j] * A[j] and so on..)

Title: Separating merged array of arithmetic and geometric series

Body:
Given an array of positive integers in increasing order. Separate them in two series, an arithmetic sequence and geometric sequence. The given array is such that a solution do exist.

The union of numbers of the two sequence must be the given array.

Both series can have common elements i.e. series need not to be disjoint.

The ratio of the geometric series can be fractional.

Example:

```<code>Given series : 2,4,6,8,10,12,25
AP: 2,4,6,8,10,12
GP: 4,10,25
</code>```

I tried taking few examples but could not reach a general way. Even tried some graph implementation by introducing edges if they follow a particular sequence but could not reach solution.

OwnerDisplayName: MBo


答:
You can do this in linear time.

First, notice that a geometric progression is just an arithmetic progression in the elementwise logarithm of the sequence.  So we can think of having a sequence of pairs of numbers that we want to cover with a progression that is arithmetic in the first element and a progression that is arithmetic in the second element.

Two of the first three elements must lie in the same progression.  Without loss of generality, I'll assume it's the arithmetic progression.  You can find, in linear time, the longest arithmetic sequence with the right beginning and common difference that is a subsequence of your input.  You do that and then you're left with a bunch of uncovered elements; say their logarithms are g_1, g_2, ..., g_k.

Find the "greatest common divisor" of g_2-g_1, ..., g_k-g_1 --- I want the biggest real number d such that g_2-g_1, g_3-g_1, ..., g_k-g_1 can all be written as multiples of d.

Then, if there is a geometric progression covering g_1, ..., g_k that is a subsequence of your input, there must be one with common ratio d.  All you need to do is check that g_1, g_1 * exp(d), g_1 * exp(2d), ..., g_k are all elements of your input, and you can do this in linear time.

So you do the above six times (twice --- arithmetic and geometric --- for each of the three possible choices of "first two"), and the above takes linear time.

OwnerDisplayName: tmyklebu


问:
What does "polyadic" mean in the context of functional programming and type systems?
And how does it (or does not) correspond to "polymorphic"? Occasionally I see this notion like in: Implement and represent polyadic operations. I checked Wiktionary but it only gives a general meaning, not specific to functional programming.</p>

答:
It's really simple to understand.

A function that takes zero arguments is called niladic function.

A function that takes one argument only is called monadic function.

A function that takes two arguments is called dyadic function.

A function that takes three arguments it called triadic function.

A function that takes multiple arguments is called polyadic function.

A function that takes a variable number of arguments is called variadic function.

How does this relate to polymorphy? Imho it does not relate to polymorphy at all. I think often times polyadic and variadic are substitutable. See wikipedia for further information.

How does this relate to functional programming?

I think the following wikipedia quote sais it all:

There are many mathematical and logical operations that come across naturally as variadic functions.
  For instance, the summing of numbers or the concatenation of strings
  or other sequences are operations that can logically apply to any
  number of operands.


答:
This problem can be tackled using Decorator pattern. Just keep Container related to Compound, and turn Version into a decorator of Compound.

Using the reference diagram here, your problem could be mapped this way:

Component = Compound

ConcreteComponent = concrete Compound that holds Structures

Decorator = Version Concrete

Decorator = version of models or packs of extras

Hope it helps.

Title: OOP Design: relationship between entity classes

Body:
I have at first sight a simple issue but can't wrap my head around on how to solve. I have an abstract class Compound. A Compound is made up of Structures. Then there is also a Container which holds 1 Compound.

A "special" implementation of Compound has Versions. For that type of Compound I want the Container to hold the Versionof the Compound and not the Compound itself.

You could say "just create an interface Containable" and a Container holds 1 Containable. However that won't work. The reason is I'm creating a framework and the main part of that framework is to simplify storing and especially searching for special data type held by Structure objects. Hence to search for Containers which contain a Compound made up of a specific Structure requires that the "Path" from Containerto Structure is well defined (Number of relationships or joins).

I hope this was understandable. My question is how to design the classes and relationships to be able to do what I outlined.

EDIT:

Kind of translation issue. with version i did not mean in terms of "versioning" but more in terms of "different variety" but fundamentally the same. There is no active / inactive. All are active.

EDIT 2:

Also note that these classes are entity classes and hence complex inheritance and hierarchies can be problematic.

EDIT 3:

Just don't see how either pattern (Composite, decorator) can work. I tried but the problem is the "path traversal", eg. implementing it in the context of Spring-data and QueryDSL.

I've created Class diagramm with comments that might help to understand the issue. Batch = Version.


答:
Honestly, there are a few programming books that I read as avidly as one usually reads a novel. Just look for the most interesting ones, and reading them will not be a problem at all.

Don't just limit yourself to exclusively technical books; a lot of interesting books about programming are interviews, essays, success stories, things like that. I find those extremely fascinating and still informative. They might be a good starting point for you.

Title: How do people read big technical books?

Body:
I see that most of the good programmers have the habit of reading big books for learning about technology.

What does it really take to read technical books, apart from the real interest on the technology?

How can I improve my ability to read these books?


问:
Get/Post Controller Logic Best Practice
In an ASP.NET MVC project (Razor), I have a Get request, which loads two properties on a model, dependent on the property passed into the action method.  So if the parameter has a value, the Group property is supplied data.  But if not, the Groups collection property is supplied data.

In the post action method, when I process the data, to repopulate the view, I have to provide similar logic, and could getaway with returning Action(param) (the get response) to the caller.

My question is, based on experience, is that a good practice to get into?  I see some downsides to doing that, but adds the lack of code redundancy.  Or is there a better alternative?

答:
Do you have to create the view from the POST?  A nicer pattern might be to use Post/Redirect/Get; this way the data is POSTed to the action which simply returns a 302 redirect to the GET action with the appropriate parameters in the query string.  The responsibility for rendering then remains with the GET whilst altering state on the server is kept within the 'POST'.

The additional benefit of doing this is that you solve the problem of user's making duplicate
requests when refreshing the page.

In terms of Best Practice when working with the web, it might be worthwhile learning more about REST and trying to apply RESTful principles to your MVC application.

Title: Get/Post Controller Logic Best Practice


问:
How to create contracts in python
I am currently learning Python (from Java) and have a question on contracts.

Example: an application defines an interface that all plugins must implement and then the main application can call it.

In Java:

```<code>public interface IPlugin {
  public Image modify(Image img);
}

public class MainApp {
   public main_app_logic() {
     String pluginName = "com.example.myplugin";
     IPlugin x = (IPlugin) Class.forName(pluginName);
     x.modify(someimg);
   }
}
</code>```

The plugin implements the interface and we use reflection in main app to call it. That way, there's a contract between the main app and the plugin that both can refer to.

How does one go about doing something similar in Python? And also, which approach is better?

P.S. I'm not posting this on SO because I'm much more concerned with the philosophy behind the two approaches.

答:
Python, being a dynamic programming language, does not usually require the rigidity of Java contracts.

If you are looking for a plugin-style registry, the python distribution packaging library setuptools provides methods to register "entry points"; using the pkg_resources module (part of the setuptools project) you can then enumerate everything registered for a given entry point, and different packages can register their plugins that way. See Explain Python entry points.

Python does provide 'contracts' of a sort, called Abstract Base Classes. Their purpose is more to test if an object can satisfy the contract, and is not normally used for discovery.

Last but not least, the add-on packages zope.interface and zope.component (part of the Zope Component Architecture) provide both a method to specify contracts, and the means to look up components registered as implementing a given contract.

Title: How to create contracts in python