问:
Do I have to internationalise the display of hexadecimal values?
For decimal numbers, obviously I want to localise everything. Whatever programming language I'm working in, there will tend to be tools for this, so it's also easy to do.

In my application, I happen to be formatting numbers as hexadecimal quite often. This leads me to wonder:

Are there locales which group hexadecimal numbers into different groupings to me?

Are there locales which use a separator other than space for the groupings?

Are A-F used as the extra six digits even in locales which don't use a Latin script?

I guess in general - do I have to internationalise this, or does everyone in the world look at the same hexadecimal value and intrinsically understand it the same way?

答:
Generic answer: If the requirements are not clear, or unknown, you can approach this in two ways. The first is YAGNI, and don't do it. The other is to plan ahead and create a locale for displaying Hex numbers, and only implement a single format. </p>

<p>In your case, given the target audience, I would spend a short (something over a second, less than a minute is about right) amount of time asking the product owner for requirements, and then apply YAGNI. The reason for asking is so you don;t get blamed for not implementing a requirement you did not know about, and have evidence you planned ahead. </p>

Body:
Generic answer: If the requirements are not clear, or unknown, you can approach this in two ways. The first is YAGNI, and don't do it. The other is to plan ahead and create a locale for displaying Hex numbers, and only implement a single format.

In your case, given the target audience, I would spend a short (something over a second, less than a minute is about right) amount of time asking the product owner for requirements, and then apply YAGNI. The reason for asking is so you don;t get blamed for not implementing a requirement you did not know about, and have evidence you planned ahead.


问:
What exactly is the Garbage Collector in Java?
I think I generally know what the Garbage Collector in Java does, but It's praised a lot, so I thought maybe I'm missing something about it's functionality.

What I know is, that the GC takes care of erasing from the memory objects that have no reference to them, and thus are unreachable by the programmer.

For example, if inside a loop I'm constantly creating a new Object(), the previous ones will eventually get deleted by the GC (correct me if I'm wrong).

This is very useful for me as a Java programmer, and spares me a lot of headache that I assume C++ programmers have to deal with - manually deleting objects from the memory (again, correct me if I'm wrong).

This feature is awesome, but is there anything more to the Garbage Collector? Am I missing something?

答:
For the visually minded, here's a parable by Kieron Briggs:

Picture a big empty room with a big furnace/incinerator type thing at one end. Hanging form the roof are a number of ropes, called Threads. Attached to the various threads are little sparkly Objects, and those Objects can have other Object attached to them in turn by little rods called References. This creates a (hopefully) beautiful structure of Objects all attaches (either directly or indirectly) to a Thread. You can even have Objects which link to more than one Thread.

When an Object isn't needed any more, the Reference to it disappears. If that leaves the Object (or a whole collection of Objects) unattached to any Thread, it will fall down onto the floor and shatter. This gradually builds up a layer of broken objects lying around the floor. In a language like C, eventually the floor would become so full that there was no room for more Objects, and Bad Things would happen.

But in Java, we have a Garbage Collector. This is a little dude in overalls that climbs down a special Staff Only Thread, sweeps up all the broken Objects on the floor, and shovels them into the incinerator. You never know exactly when he's going to come along, but he's always there keeping an eye on the mess on the floor to make sure that it doesn't fill up too much...

more formal description: mark-and-sweep algorithm

...each object in memory has a flag (typically a single bit) reserved for garbage collection use only. This flag is always cleared, except during the collection cycle. The first stage of collection does a tree traversal of the entire 'root set', marking each object that is pointed to as being 'in-use'. All objects that those objects point to, and so on, are marked as well, so that every object that is ultimately pointed to from the root set is marked. Finally, all memory is scanned from start to finish, examining all free or used blocks; those with the in-use flag still cleared are not reachable by any program or data, and their memory is freed. (For objects which are marked in-use, the in-use flag is cleared again, preparing for the next cycle.)

ContentLicense: CC BY-SA 3.0


问:
How to slow down your computer (for testing purposes)?
As most people agree, encouraging developers to make  fast code by giving them slow machines is not a good idea. But there's a point in that question. My dev machine is fast, and so I  occasionally write code that's disturbingly inefficient, but that only becomes apparent when running it on other people's machines.

What are some good ways to temporarily slow down a turbocharged dev machine? The notion of "speed" includes several factors, for example:

CPU clock frequency.

Amount of CPU cores.

Amount of memory and processor cache.

Speed of various buses.

Disk I/O.

GPU.

etc.

答:
Anything that you do to slow down your machine would probably be a hack.

Here are a couple of suggestions:

Use virtual machines

Profile the code on your machine, looking for bottlenecks

Use an old machine for "performance testing"

ContentLicense: CC BY-SA 2.5


问:
Constants vs public properties for configuration
My application has a few high level configuration options such as directories which will be used for various things, database connection information and a few other settings which are required for the application to run.

I'm debating with myself whether or not constants are better than variables for this purpose and would like some input.

By having:

```<code> $config = new Config;
 new Whatever($config->foo, $config->bar);
</code>```

Instead of:

```<code>new Whatever(Config::FOO, Config::BAR);
</code>```

I get the power of polymorphism, I can quickly swap between configuration settings by instantiating $config as a different class with the same class members.

There's obviously a trade-off here. Anything which needs the config options must instantiate a $config object, using memory and creating extra code as well as making it so the config options are no long immutable.

The immutability problem could by solved with a method e.g. $config->get('Foo'); so that is potentially a non-issue, although it does add to verbosity and a method call is more expensive than reading a constant or variable.

答:
For configuration options, it is better to use properties (or methods) instead of constants. The reason for this is that configuration options will change when you deploy your application in a different environment.

When using properties/methods, you can opt to read the relevant values from a configuration file at startup, which is not possible if you use constants.

The overhead of creating a Config object can be minimized by having one global object and making that available throughout the application using either Dpendency Injection or the Singleton pattern.

Worrying about the overhead of a function call is most likely premature optimization. It is unlikely to matter and in the rare cases where it does (e.g. in a tight loop), there are other solutions, like reading the configuration value at a non-critical time and caching the value in a property/variable.


问:
Usage of mix licensies in commercial use
I'm developing a CMS, inside it I use many various plugins/addons wich licenses mostly like MIT, GNU, GPL (such as jQuery, nivoSlider, DataTables and so on..). After reading those licenses I believe I can use them inside my CMS and charge users for my CMS.

In my project I have a specific folder where I store all these plugins with their license and all notices. Is this the correct way? Or should I somewhere on my site notice the all plugins Im using with the path where they can be found in my project folder?

What about if I would use my CMS as SaaS? The end users would not have the access to source files so I would not exactly be distributing it. Is it posible?

And lastly, can I protect my own source files with the license? Wouldnt it collide with the other ones? I would like to protect it as much as I can at least in a legal way as I cannot really protect it as all PHP files are easy accessible.

Thank you for any help. Also note that I have read a lot about license, but these are things I would like to confirm or to see if I misunderstood something.

答:
The MIT and BSD licenses allow you to use them as a library and still keep your work under any license you want. The GPL, on the other hand, doesn't allow this. When you use a GPL library, the whole project must be GPL. There is a special version of the GPL, the LGPL (Library GPL or Lesser GPL) which specifically allows to use the library in non-GPL projects.

But the GPL only applies to distribution of software. When you provide the software as a service, you don't distribute the software. That means you do not need to provide the sorcecode to anyone. There is a special version of the GPL, the AGPL (Affero GPL) which closes this loophole and requires you to license the software to anyone who uses it via network.


问:
Push response to the user for which the request is created in Asp.Net (Chat Server)
I am working on a Chat Server Application in Asp.Net with C#.

Suppose there are 5 users online say User A,B,C,D,E. Suppose A sends a message in chatbox to user B, so how the chatbox (Textbox/Textarea of chat) of User B will load the new content?

One Option is to refresh the chatbox every 10Seconds or 15 seconds but it's pretty unuseful way because as if there is no new message for the user the chatbox will still be refreshed.

I have an aspx page say client.aspx with client.aspx.cs as code behind file and server file say server.cs.
There is a send button on aspx page on click event of this button i called a method of my server file say UpdateChatbox(from,to,content) now the from is User A, to is User B and content is my msg in chatbox,
Now the question is :
How Server.cs file update the ChatBox on client.aspx page of User B?

答:
Without knowing exactly how your Server and Client looks like...

How about setting it up so when the Server receives a new message it will fire of an event to all clients that are online, and make sure that the clients hook into these events.

As I said, there's not really much to go on since you don't go deeper into how the Server and Client looks like and are set up, but this seems to be the most straight-forward approach.


问:
Self-organization during Sprint Planning
During Sprint Planning there are a lot of decisions to be made:

How many PBIs should the team commit to?

Which tasks should constitute each PBI?

How much time should each task take?

With no team leader it is not always easy to make all these decisions, since there will be some decision points (sometimes more than a few) in which the team members will disagree.

I thought about a few options to deal with such disagreements when a consensus cannot be reached in a short period of time (we don't want endless arguments).

Let ScrumMaster decide

Let the person who will most likely work on the story decide.

Majority vote

Let the person who actually writes the tasks in Excel decide (in such case have a different person write the tasks for each story).

I have two questions:

How to measure consensus? Should the Scrum Master ask each person whether they agree with every decision proposed?

When no consensus can be reached shortly, which option from the list that I proposed do you think we should choose, if any?

Thank you!

答:
First, the only ones that can decide how much work they take on, are the team members. They have to commit to the work. If somebody else (Scrum Master/Team Leader/...) would decide, it wouldn't work, because then the team could blame somebody else for assigning to much work, if they didn't finish.

Apply the concepts of time boxing and an "anonymous" estimation technique like Planning Poker to achieve consensus. Example: Give the team 2 minutes to briefly discuss the story. Make them play a round of poker (there's the possibility to give your own judgement without knowing what the others will do). If they agree, fine. If they differ slightly, it's usually easy to settle for one. In case of uncertainty, take the higher estimate. If they strongly disagree. Give them another 2 minutes to discuss why. Then play another round of planning poker. In my experience, this approach leads to a consensus pretty fast. You could call this an iterative majority vote...

After the estimation, every team member should have a pretty good idea what needs to be done in order to complete the story. Otherwise they did not understand the problem in the first place and were unable to give a good estimation. In consequence, every team member should be able to break down the stories to tasks. However, this is unrelated to estimating and taking on stories. In my opinion, concrete tasks should be defined only after the the sprint's stories were selected. Everything else ruins the relative-estimation idea. Usually, we just each select a story and break it down, till all tasks are defined. Then the breakdown is reviewed by the members that didn't do it. Takes less than 15 minutes.


问:
Creating a very basic compiler using Java
I want to try and create my own very basic language, with it's very basic compiler. All using Java.

For now, it will only need to enable to 'programmer' to print things to the screen.

I had an idea for how to do this, and what I wanted to know is: Will this be considered an actual 'compiler', an actual 'language', and an actual 'virtual machine'? (All very, very basic of course).

My idea was to create a program which will serve as the 'IDE' (editor and compiler), and another one which will serve as the 'virtual machine'.

This means that the IDE will not compile the written code to some existing machine code, like the Java Bytecode, but will actually compile to some kind of compiled code made up by me.

This compiled code will only be understandable by my 'virtual machine' program, and will only be able to run inside this program. The 'virtual machine' program, will use high-level Java operations in order to understand and execute the compiled code.

The 'virtual machine' program will be a Java program, running on the JVM.

My question is: Conceptually, is this considered a virtual machine, and 'machine code'?
If not, is this still considered a 'programming language', even though it's compiled bytecode can only run inside a specific program?

答:
Sure it is. Everything that introduces another level of interpretation into the computing stack is a virtual machine that a programmer can target. It may not become a very complete or successful one unless you put insane amounts of effort into it, but your claim to the technical term is valid.

"Machine code" is a more restricted term. Surprisingly, the convention is not to call code that runs on a virtual machine "machine code", but "byte code". "Machine code" is usually understood to mean code to be run on a physical microprocessor, i.e. a stream of its opcodes. Anything below that is micro code, and anything above is either "byte code" or just "code" (Java code, Python code, etc.)


答:
How to measure consensus? Should the Scrum Master ask each person whether they agree with every decision proposed?

I prefer thumb voting or fist of five for checking consensus. Having everybody express their opinion simultaneously makes it less likely for the opinions of strong personas in the team to affect others.

Let ScrumMaster decide

Role of Scrum Master is to serve and coach the team. I don't think he should make decisions on how team does their work.

Let the person who will most likely work on the story decide.

People who work on a story are the ones responsible for it and should have the power to make decisions on it. However decisions about details should be deferred until work on a story starts. Sprint planning should be quite high-level.

Majority vote

This sounds best to me. Measure consensus, discuss, vote again until consensus has been achieved. Note that consensus does not mean everybody agrees, it means nobody wants to block progress. If somebody wants to block progress, you need to discuss it, no matter how much in a hurry you are.

Let the person who actually writes the tasks in Excel decide (in such case have a different person write the tasks for each story).

Does this mean splitting stories in to tasks? If so, it is similar to number two, those who work on the story also split it in to tasks and make decisions that need to be made.

Title: Self-organization during Sprint Planning

Body:
During Sprint Planning there are a lot of decisions to be made:

How many PBIs should the team commit to?

Which tasks should constitute each PBI?

How much time should each task take?

With no team leader it is not always easy to make all these decisions, since there will be some decision points (sometimes more than a few) in which the team members will disagree.

I thought about a few options to deal with such disagreements when a consensus cannot be reached in a short period of time (we don't want endless arguments).

Let ScrumMaster decide

Let the person who will most likely work on the story decide.

Majority vote

Let the person who actually writes the tasks in Excel decide (in such case have a different person write the tasks for each story).

I have two questions:

How to measure consensus? Should the Scrum Master ask each person whether they agree with every decision proposed?

When no consensus can be reached shortly, which option from the list that I proposed do you think we should choose, if any?

Thank you!

ContentLicense: CC BY-SA 4.0


答:
A similar analogy to gnat's answer is to imagine someone sat at a desk in a paper based office. The person performs tasks using paper documents (objects) and needs to have these bits of paper on their desk. When they have finished and no longer need to reference a document they throw it in the bin.

The desk and the bin have a finite capacity (memory). The GC is the janitor who comes along occasionally and empties the bin so that capacity isn't exceeded*.

*Of course you can always run out of memory by putting too many documents on your desk. There's nothing the janitor can do about this.

Title: What exactly is the Garbage Collector in Java?

Body:
I think I generally know what the Garbage Collector in Java does, but It's praised a lot, so I thought maybe I'm missing something about it's functionality.

What I know is, that the GC takes care of erasing from the memory objects that have no reference to them, and thus are unreachable by the programmer.

For example, if inside a loop I'm constantly creating a new Object(), the previous ones will eventually get deleted by the GC (correct me if I'm wrong).

This is very useful for me as a Java programmer, and spares me a lot of headache that I assume C++ programmers have to deal with - manually deleting objects from the memory (again, correct me if I'm wrong).

This feature is awesome, but is there anything more to the Garbage Collector? Am I missing something?


答:
There is one more thing you can do with GC besides simply offloading your memory management to it: weak references, which could be used to offload your caches management onto GC as well.

Your weak objects are reachable and can still be used at some point, but you're instructing GC that it's ok to get rid of them at any moment, and you don't really mind losing them.


问:
What exactly is Virtual Machine Bytecode?
I want to work on a very simple compiler for a very simple language. The compiler will compile the code to some basic bytecode. Later, a virtual machine program will run the bytecode, and execute the program.

I have several questions about what bytecode actually is:

Does bytecode have to be of binary form, aka composed of only 1 and 0
sequences? Or can it include more kinds of numbers, and even words?

How exactly, most commonly, is the bytecode of a program composed? One
idea I had for what the bytecode will contain and how it will be
composed, using my compiler, is: The compiler will scan the developer's code, and convert each command to some bytecode equivalent. For example, the command print will be converted to 1 in the bytecode. Later, when the VM runs the bytecode, each element in the bytecode will be converted to some execution in the program. For example, if the VM scans the bytecode and comes acorss 1, it will print something. Is this approach common? Is it valid? What is the most common approach to how and what the bytecode composes?

答:
there is no need to go binary, you can write out text and interpret that directly. Most VMs will use octet-based binary for efficiency.

that is entirely up to the designer. however usually the common instructions (adding 2 numbers, GOTOs,...) will be shorter than the uncommon ones (calling a function, raising an exception,...)

one way to do this is to let the first few bits of an opcode decide the family (arithmatic, comparison, jumps,...) of the instruction, the next few bits will be the specific instruction, and the last bits will indicate the operands used (if applicable)


问:
Exceptions: Why throw early? Why catch late?
There are many well-known best practices about exception handling in isolation. I know the "do's and don'ts" well enough, but things get complicated when it comes to best practices or patterns in larger environments. "Throw early, catch late" - I've heard many times and it still confuses me.

Why should I throw early and catch late, if at a low-level-layer a null pointer exception is thrown? Why should I catch it at a higher layer? It doesn't make sense for me to catch a low-level exception at a higher level, such as a business layer. It seems to violate the concerns of each layer.

Imagine the following situation:

I have a service which calculates a figure. To calculate the figure the service accesses a repository to get raw data and some other services to prepare calculation. If something went wrong at the data retrieval layer, why should I throw a DataRetrievalException to higher level? In contrast I would prefer to wrap the exception into a meaningful exception, for example a CalculationServiceException.

Why throw early, why catch late?

答:
Throw as soon as you see something worth throwing for to avoid putting objects in an invalid state. Meaning that if a null pointer was passed you check for it early and throw a NPE before it has a chance to trickle down to the low level.

Catch as soon as you know what to do to fix the error (this is generally not where you throw otherwise you could just use a if-else), if an invalid parameter was passed then the layer that provided the parameter should deal with the consequences.


答:
In my experience, its best to throw exceptions at the point where the errors occur.  You do this because it's the point where you know the most about why the exception was triggered.

As the exception unwinds back up the layers, catching and rethrowing is a good way to add additional context to the exception. This can mean throwing a different type of exception, but include the original exception when you do this.

Eventually the exception will reach a layer where you are able to make decisions on code flow (e.g a prompt the user for action). This is the point where you should finally handle the exception and continue normal execution.

With practice and experience with your code base it becomes quite easy to judge when to add additional context to errors, and where it's most sensible to actually, finally handle the errors.

Catch → Rethrow

Do this where you can usefully add more information that would save a developer having to work through all the layers to understand the problem.

Catch → Handle

Do this where you can make final decisions on what is an appropriate, but different execution flow through the software.

Catch → Error Return

Whilst there are situations where this is appropriate, catching exceptions and returning an error value to the caller should be considered for refactoring into a Catch → Rethrow implementation.

Title: Exceptions: Why throw early? Why catch late?

Body:
There are many well-known best practices about exception handling in isolation. I know the "do's and don'ts" well enough, but things get complicated when it comes to best practices or patterns in larger environments. "Throw early, catch late" - I've heard many times and it still confuses me.

Why should I throw early and catch late, if at a low-level-layer a null pointer exception is thrown? Why should I catch it at a higher layer? It doesn't make sense for me to catch a low-level exception at a higher level, such as a business layer. It seems to violate the concerns of each layer.

Imagine the following situation:

I have a service which calculates a figure. To calculate the figure the service accesses a repository to get raw data and some other services to prepare calculation. If something went wrong at the data retrieval layer, why should I throw a DataRetrievalException to higher level? In contrast I would prefer to wrap the exception into a meaningful exception, for example a CalculationServiceException.

Why throw early, why catch late?


问:
Why does it seem so hard for non programmers to understand versioning?
In the past I have worked with designers, BAs and project managers, all who regularly produce project artifacts, yet very really do they understand the concept of versioning.  When I try to explain it to them (even in its most simple form of multiple differently named files) they seem to have some kind of mental block.  Why do you think this is?</p>

答:
You mention that even simple document versioning is giving people difficulties, so maybe you're not explaining it well, or your team are not that bright.

Our developers use git on the commandline for versioning, and once they're up the learning curve, they all cope fine with it.  I haven't bothered trying to explain git to non-technical staff because with them there is much less direct collaboration on individual documents - for this stuff we use DropBox, and I've not seen anyone struggle yet.


答:
What you are doing, effectively, is designing new computer instructions, along with a new computer (your virtual machine) implemented as a program.

Generally, instructions (which is what byte-codes are) have an initial part that the interpreter examines to work out what is coming next. For example, as you have suggested, 1 could mean print the following string. 2 might mean add the following 2 integers.

As you work out what instructions you need, you will find that you need a way of holding data (called the memory organization), and a way of organizing the instructions. Will the instructions do very complex things, or very simple things? If they do complex things (print this string) then many will be needed, but the data can be organized in a simpler way. If the instructions do simple things (load this integer to work area 1) there can be fewer instructions, but the data organization will need to support richer structures and more data types.

Start simple, say with 1-byte op-codes. Expect to go through many code versions as you work it out.

Enjoy. You will learn more about how computers work than you imagine.

Title: What exactly is Virtual Machine Bytecode?

Body:
I want to work on a very simple compiler for a very simple language. The compiler will compile the code to some basic bytecode. Later, a virtual machine program will run the bytecode, and execute the program.

I have several questions about what bytecode actually is:

Does bytecode have to be of binary form, aka composed of only 1 and 0
sequences? Or can it include more kinds of numbers, and even words?

How exactly, most commonly, is the bytecode of a program composed? One
idea I had for what the bytecode will contain and how it will be
composed, using my compiler, is: The compiler will scan the developer's code, and convert each command to some bytecode equivalent. For example, the command print will be converted to 1 in the bytecode. Later, when the VM runs the bytecode, each element in the bytecode will be converted to some execution in the program. For example, if the VM scans the bytecode and comes acorss 1, it will print something. Is this approach common? Is it valid? What is the most common approach to how and what the bytecode composes?


问:
Locking techniques
Delphi RAD libraries implement many thread friendly objects in a way which forces one to declare another object for storing the reference returned by that object's locking method. The object thus essentially encapsulates the prime object which is returned on locking. For example;

```<code>List := ThreadList.Unlocklist;
// do something with List
ThreadList.LockList;
</code>```

Why is this approach taken? Why is inheriting from the prime object, adding the locking object, overriding constructors and destructors, discouraged? For example the following implementation adds a TMREWSync to a list;

```<code>IMREWS = interface

  ['{5B6DE5FA-847B-42D5-8BF4-9EB20A452C54}']

  procedure BeginRead;
  function  BeginWrite: Boolean;
  procedure EndRead;
  procedure EndWrite;

end;

TThreadList = class ( TList, IMREWS )
private

  FLock : TMREWSync;

public

  constructor Create;
  destructor  Destroy; override;

  property Lock : TMREWSync read FLock implements IMREWS;

end;

constructor TThreadList.Create;
begin
  FLock := TMREWSync.Create;
  inherited;
end;

destructor TThreadList.Destroy;
begin
  inherited;
  FLock.Free;
end;

// Usage:

ThreadList.BeginWrite;
// Do something with ThreadList
ThreadList.EndWrite;
</code>```

答:
when inheriting you fall into the load-modify-store trap

say you want to increase an object's priority:

```<code>int prio = myObject.getPriority();
myObject.setPriority(prio+1);
</code>```

now consider what happens when another thread wants to lower the priority:

```<code>int prio = myObject.getPriority();
myObject.setPriority(prio-1);
</code>```

one interleaved sequence of calls could be:

```<code>//thread1         //thead2
int prio1 = myObject.getPriority();
                  int prio2 = myObject.getPriority();
myObject.setPriority(prio1+1); // now is prio+1
                  myObject.setPriority(prio2-1); now is 2 lower than expected
</code>```

there are several other options which are nearly all bad

this can be solved by encapsulating the operation in a method but that quickly becomes unfeasible for complex operations involving multiple objects

plus if the object changes you need to modify the locking subclass to include the new methods

Title: Locking techniques

Body:
when inheriting you fall into the load-modify-store trap

say you want to increase an object's priority:

int prio = myObject.getPriority();
myObject.setPriority(prio+1);

now consider what happens when another thread wants to lower the priority:

int prio = myObject.getPriority();
myObject.setPriority(prio-1);

one interleaved sequence of calls could be:

//thread1         //thead2
int prio1 = myObject.getPriority();
                  int prio2 = myObject.getPriority();
myObject.setPriority(prio1+1); // now is prio+1
                  myObject.setPriority(prio2-1); now is 2 lower than expected

there are several other options which are nearly all bad

this can be solved by encapsulating the operation in a method but that quickly becomes unfeasible for complex operations involving multiple objects

plus if the object changes you need to modify the locking subclass to include the new methods


答:
You want to throw an exception as soon as possible because that makes it easier to find the cause. For example, consider a method that could fail with certain arguments. If you validate the arguments and fail at the very beginning of the method, you immediately know the error is in the calling code. If you wait until the arguments are needed before failing, you have to follow the execution and figure out if the bug is in the calling code (bad argument) or the method has a bug. The earlier you throw the exception, the closer it is to its underlying cause and the easier it is to figure out where things went wrong.

The reason exceptions are handled at higher levels is because the lower levels don't know what's the appropriate course of action to handle the error. In fact, there could be multiple appropriate ways to handle the same error depending on what the calling code is. Take opening a file for example. If you're trying to open a config file and it's not there, ignoring the exception and proceeding with the default configuration can be an appropriate response. If you're opening a private file that's vital to the program's execution and it's somehow missing, your only option is probably to close the program.

Wrapping the exceptions in the right types is a purely orthogonal concern.


答:
SignalR is what you are looking for.

From the website:

ASP.NET SignalR is a new library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and client. Servers can now push content to connected clients instantly as it becomes available. SignalR supports Web Sockets, and falls back to other compatible techniques for older browsers. SignalR includes APIs for connection management (for instance, connect and disconnect events), grouping connections, and authorization.

You can have a look inside JabbR source code to see what it can do and how to do it.

Title: Push response to the user for which the request is created in Asp.Net (Chat Server)

Body:
I am working on a Chat Server Application in Asp.Net with C#.

Suppose there are 5 users online say User A,B,C,D,E. Suppose A sends a message in chatbox to user B, so how the chatbox (Textbox/Textarea of chat) of User B will load the new content?

One Option is to refresh the chatbox every 10Seconds or 15 seconds but it's pretty unuseful way because as if there is no new message for the user the chatbox will still be refreshed.

I have an aspx page say client.aspx with client.aspx.cs as code behind file and server file say server.cs.
There is a send button on aspx page on click event of this button i called a method of my server file say UpdateChatbox(from,to,content) now the from is User A, to is User B and content is my msg in chatbox,
Now the question is :
How Server.cs file update the ChatBox on client.aspx page of User B?


答:
You're not missing anything. However, I would like to point out something that I don't think any of the other answers have addressed clearly. Garbage collection is about program correctness and security first and foremost; convenience is secondary (although it is very convenient.)

If the programmer manages memory manually, making a mistake means you corrupt the program's state. The program keeps going but execution's gone off the rails and no longer has any meaning. It could fail catastrophically right away, but will probably keep going in a way that's seemingly correct but very subtly wrong, possibly for days or weeks before anyone notices the problem. Even worse is that memory bugs could be exploited by attackers. If the buggy program runs with administrator privileges, and the bug allows an attacker to run arbitrary code, the potential for damage is almost unlimited. This sort of bug is very hard to detect and impossible to avoid; sooner or later you will introduce a memory bug because we're all human. A language that outright forbids manual memory management is guaranteed to be free of this type of bug (though memory bugs are definitely not the only way to introduce a security vulnerability.)

Lack of garbage collection generally precludes complicated object structures. For the most part you're limited to creating objects that either always exist, or have a single owner that's responsible for deleting them. That rules out, for example, persistent data structures, because any given node could be shared by many objects and there's no reliable way of managing that. Using smart pointers with reference counting is not a solution - their performance is bad and cylic references (two objects pointing to each other) won't be freed. You can introduce weak references to avoid the latter problem, but now you've made manual memory management even harder to get right (and the performance is still bad). Garbage collection enables these complicated data structures to be cleaned up correctly and in an efficient manner.

Ironically, being deprived of persistent data structures makes the program harder to reason about, because changes to the data structure are destructive and now you have to be very careful about who has references to it and who's making changes to it. So on top of memory bugs, you have to worry about additional state/aliasing bugs as well.


答: One inarguable reason for taking that approach is because an object has a lock as opposed to is a lock. As soon you get is a / has a correct, everything gets simpler.</p>

Title: Locking techniques

Body:
Delphi RAD libraries implement many thread friendly objects in a way which forces one to declare another object for storing the reference returned by that object's locking method. The object thus essentially encapsulates the prime object which is returned on locking. For example;

```<code>List := ThreadList.Unlocklist;
// do something with List
ThreadList.LockList;
</code>```

Why is this approach taken? Why is inheriting from the prime object, adding the locking object, overriding constructors and destructors, discouraged? For example the following implementation adds a TMREWSync to a list;

```<code>IMREWS = interface

  ['{5B6DE5FA-847B-42D5-8BF4-9EB20A452C54}']

  procedure BeginRead;
  function  BeginWrite: Boolean;
  procedure EndRead;
  procedure EndWrite;

end;

TThreadList = class ( TList, IMREWS )
private

  FLock : TMREWSync;

public

  constructor Create;
  destructor  Destroy; override;

  property Lock : TMREWSync read FLock implements IMREWS;

end;

constructor TThreadList.Create;
begin
  FLock := TMREWSync.Create;
  inherited;
end;

destructor TThreadList.Destroy;
begin
  inherited;
  FLock.Free;
end;

// Usage:

ThreadList.BeginWrite;
// Do something with ThreadList
ThreadList.EndWrite;
</code>```


答:
A valid business rule is 'if the lower level software fails to calculate a value, then ...'

This can only be expressed at the higher level, otherwise the lower level software is trying to change its behavior based on its own correctness, which is only going to end in a knot.


问:
What is the most productive way to handle development-related failures?
We've all been there:

Your project failed or got cancelled.

The code you spent days working on got rejected by your team.

The design pattern you introduced to the team created chaos.

Everyone ignores your ideas.

My question is, what is the most productive way for a programmer to handle development-related failures such as these?

答:
They're not failures - they are experiences

You learn and grow from your experiences by reflecting on how they made you feel and if you want more of that feeling.

If it's a bad experience (like that list you offered) then the accompanying bad feeling is probably something you'll want to avoid (assuming you not so thick-skinned that you didn't care about the impact of your actions).

Overall, don't get too involved in comparing yourself to others, they're having just as much trouble working through it all as you are.


问:
Pattern for multiple datasources
I've already read this question on CodeReview.  I was hoping for general advice.

I'm writing a service which will go to numerous data sources. Each source requires getting copious amounts of data and changing it to a single format. What is the best pattern for a task like this?

I currently have a "base" class which exposes a static GetData method, which the other classes inherit from and implement. This doesn't seem like the cleanest approach, so I was wondering what other approaches might suit my needs?

答:
Sounds like you need a Repository pattern, maybe backed by a Strategy which would choose between different implementations.

How'd you actually do it is exposing a generic interface with your basic CRUD operations and make an implementation for each data source while letting the strategy pattern to decide on the implementation. If you're using dependency injection this might get a little tricky if deciding on which data source you're using is not easily deducted from the beginning.

Title: Pattern for multiple datasources


答:
In two years of doing scrum, we've never failed to reach consensus.  Measuring consensus is simple: just ask if there are any open concerns about the plan. Watch for people who don't speak up, but are shaking their head.  Don't end the meeting until everyone is on board. </p>

<p>The great thing about scrum is your mistakes don't last very long.  The worst I've ever had to do to gain consensus is say something like, "You may be right, but the rest of the team disagrees.  Are you willing to try it for two weeks and reevaluate in our next retrospective?" </p>

Body:
In two years of doing scrum, we've never failed to reach consensus.  Measuring consensus is simple: just ask if there are any open concerns about the plan. Watch for people who don't speak up, but are shaking their head.  Don't end the meeting until everyone is on board.

The great thing about scrum is your mistakes don't last very long.  The worst I've ever had to do to gain consensus is say something like, "You may be right, but the rest of the team disagrees.  Are you willing to try it for two weeks and reevaluate in our next retrospective?"


答:
For a simple example let's take a look at PHP's Zend Engine. This is a relatively simple VM working purely in memory, thus not having to are about serialisation etc.

In PHP the bytecode consists of 167 different opcodes which can be found in one header: http://lxr.php.net/xref/PHP_TRUNK/Zend/zend_vm_opcodes.h

All those opcodes are stored in a data structure along with some meta information in form of an array (represented as pointer to the first element)

```<code>struct _zend_op_array {
    /* ... */
    zend_op *opcodes;
    /* ... */
 }
</code>```

Each operation then has its own data structure stored in there:

```<code>struct _zend_op {
    opcode_handler_t handler;
    znode_op op1;
    znode_op op2;
    znode_op result;
    ulong extended_value;
    uint lineno;
    zend_uchar opcode;
    zend_uchar op1_type;
    zend_uchar op2_type;
    zend_uchar result_type;
};
</code>```

In there we can see multiple things:

The opcode number from the long list of opcodes is stored in the opcode field.

Each operation takes two operands (op1 and op2) and has a return value (result)

Operands and return value have types, these indicate whether they represent variables, constants or temporary values. In PHP's implementation these are stored in different places and are accessed differently.

There is an extended_value which is used i.e. in foreach loops to store some more info

The line number from the source file for reporting errors (filename is stored in the zend_op_array strucuture above)

The handler is a small optimization, directly pointing to the function implementing this.

While compiling the script the compiler will create these data structures and ensure that the operands and return value show to the same place, so with a call like foo(bar()) the return value of the call to bar will be the same temporary as the operand of the opcode pushing an argument on the functions argument stack. Wait what - argument stack!? you might ask, right: As each opcode only accepts two operands we can't directly pass the function parameters, but first ZEND_SEND_* operations fill a stack, then a ZEND_DO_FCALL/ZEND_DO_FCALL_BY_NAME operation will be executed using that stack.

Using the tool vld we can dump this compiled form:

```<code>php -dextension=modules/vld.so -dvld.active -r 'foo(bar());'
Finding entry points
Branch analysis from position: 0
Return found
filename:       Command line code
function name:  (null)
number of ops:  6
compiled vars:  none
line     # *  op                           fetch          ext  return  operands
---------------------------------------------------------------------------------
   1     0  >   INIT_FCALL_BY_NAME                                       'foo', 'foo'
         1      INIT_FCALL_BY_NAME                                       'bar', 'bar'
         2      DO_FCALL_BY_NAME                              0
         3      SEND_VAR_NO_REF                               4          $0
         4      DO_FCALL_BY_NAME                              1
         5    > RETURN                                                   null

branch: #  0; line:     1-    1; sop:     0; eop:     5
path #1: 0,
</code>```

Next step is execution. This essentially is this loop (shortened):

```<code>    while (1) {
            if ((ret = OPLINE->handler(execute_data TSRMLS_CC)) > 0) {
                    switch (ret) {
                            case 1:
                                    return;
                                    /* ... */
                            default:
                                    break;
                    }
            }

    }
</code>```

OPLINE represents the current element of our array of zend_op structures. Each op has a handler which is executed. (for seeing the correct loop: it is in zend_vm_execute.h generated by zend_vm_gen.php out of zend_vm_execute.skl and zend_vm_def.h) If the handler returns one the script/function/... we are currently executing returns, such the loop ends.

A simple opcode handler can be defined like this (see zend_vm_def.h):

```<code>ZEND_VM_HANDLER(1, ZEND_ADD, CONST|TMP|VAR|CV, CONST|TMP|VAR|CV)
{
        USE_OPLINE
        zend_free_op free_op1, free_op2;

        SAVE_OPLINE();
        fast_add_function(&EX_T(opline->result.var).tmp_var,
                GET_OP1_ZVAL_PTR(BP_VAR_R),
                GET_OP2_ZVAL_PTR(BP_VAR_R) TSRMLS_CC);
        FREE_OP1();
        FREE_OP2();
        CHECK_EXCEPTION();
        ZEND_VM_NEXT_OPCODE();
}
</code>```

This code looks similar to C but is filled into the gen script mentioned ahead.  We see that this is the opcode number 1, going by the name of ZEND_ADD which represents an addition. It requires both operands, which both can be of any kind (constants, temporaries, arbitrary variables, compiler cached variables). At the end of the operation the pointer is set to the next opcode in the array.

Body:
For a simple example let's take a look at PHP's Zend Engine. This is a relatively simple VM working purely in memory, thus not having to are about serialisation etc.

In PHP the bytecode consists of 167 different opcodes which can be found in one header: http://lxr.php.net/xref/PHP_TRUNK/Zend/zend_vm_opcodes.h

All those opcodes are stored in a data structure along with some meta information in form of an array (represented as pointer to the first element)

struct _zend_op_array {
    /* ... */
    zend_op *opcodes;
    /* ... */
 }

Each operation then has its own data structure stored in there:

struct _zend_op {
    opcode_handler_t handler;
    znode_op op1;
    znode_op op2;
    znode_op result;
    ulong extended_value;
    uint lineno;
    zend_uchar opcode;
    zend_uchar op1_type;
    zend_uchar op2_type;
    zend_uchar result_type;
};

In there we can see multiple things:

The opcode number from the long list of opcodes is stored in the opcode field.

Each operation takes two operands (op1 and op2) and has a return value (result)

Operands and return value have types, these indicate whether they represent variables, constants or temporary values. In PHP's implementation these are stored in different places and are accessed differently.

There is an extended_value which is used i.e. in foreach loops to store some more info

The line number from the source file for reporting errors (filename is stored in the zend_op_array strucuture above)

The handler is a small optimization, directly pointing to the function implementing this.

While compiling the script the compiler will create these data structures and ensure that the operands and return value show to the same place, so with a call like foo(bar()) the return value of the call to bar will be the same temporary as the operand of the opcode pushing an argument on the functions argument stack. Wait what - argument stack!? you might ask, right: As each opcode only accepts two operands we can't directly pass the function parameters, but first ZEND_SEND_* operations fill a stack, then a ZEND_DO_FCALL/ZEND_DO_FCALL_BY_NAME operation will be executed using that stack.

Using the tool vld we can dump this compiled form:

php -dextension=modules/vld.so -dvld.active -r 'foo(bar());'
Finding entry points
Branch analysis from position: 0
Return found
filename:       Command line code
function name:  (null)
number of ops:  6
compiled vars:  none
line     # *  op                           fetch          ext  return  operands
---------------------------------------------------------------------------------
   1     0  >   INIT_FCALL_BY_NAME                                       'foo', 'foo'
         1      INIT_FCALL_BY_NAME                                       'bar', 'bar'
         2      DO_FCALL_BY_NAME                              0
         3      SEND_VAR_NO_REF                               4          $0
         4      DO_FCALL_BY_NAME                              1
         5    > RETURN                                                   null

branch: #  0; line:     1-    1; sop:     0; eop:     5
path #1: 0,

Next step is execution. This essentially is this loop (shortened):

    while (1) {
            if ((ret = OPLINE->handler(execute_data TSRMLS_CC)) > 0) {
                    switch (ret) {
                            case 1:
                                    return;
                                    /* ... */
                            default:
                                    break;
                    }
            }

    }

OPLINE represents the current element of our array of zend_op structures. Each op has a handler which is executed. (for seeing the correct loop: it is in zend_vm_execute.h generated by zend_vm_gen.php out of zend_vm_execute.skl and zend_vm_def.h) If the handler returns one the script/function/... we are currently executing returns, such the loop ends.

A simple opcode handler can be defined like this (see zend_vm_def.h):

ZEND_VM_HANDLER(1, ZEND_ADD, CONST|TMP|VAR|CV, CONST|TMP|VAR|CV)
{
        USE_OPLINE
        zend_free_op free_op1, free_op2;

        SAVE_OPLINE();
        fast_add_function(&EX_T(opline->result.var).tmp_var,
                GET_OP1_ZVAL_PTR(BP_VAR_R),
                GET_OP2_ZVAL_PTR(BP_VAR_R) TSRMLS_CC);
        FREE_OP1();
        FREE_OP2();
        CHECK_EXCEPTION();
        ZEND_VM_NEXT_OPCODE();
}

This code looks similar to C but is filled into the gen script mentioned ahead.  We see that this is the opcode number 1, going by the name of ZEND_ADD which represents an addition. It requires both operands, which both can be of any kind (constants, temporaries, arbitrary variables, compiler cached variables). At the end of the operation the pointer is set to the next opcode in the array.


问:
outOfMemoryException in android emulator
I'm developing an Android application which is responsible for showing multimedia such as videos and photos to user.

I have a certain activity for a gallery of photos. In my phone where I'm developing the application everything works correctly. Currently I'm testing it in an emulator with a small screen for checking for layout mistakes and I noticed that the gallery activity crashes when scrolling through photographs by throwing an outOfMemoryException.

My phone where I was developing the application is a Samsung S Advance, which I think is average, not something really powerful, just a phone with normal specs.

Should I be worried about that exception I'm getting in the emulator or is it something that will never happen in real-world conditions?

答:
With the emulator, you set the amount of memory when you start it up, and usually its defaults I believe are far less than you would normally have on your phone.  Even on a regular phone, there are many pitfalls that will cause an outOfMemoryException, e.g. memory leaks (easier than one might think), loading more bitmap data than the resolution / size supports, loading all your images at once, etc.  </p>

<p>In general, if you're getting an outOfMemoryException on an actual phone, it tends to be one of the coding errors mentioned above.  </p>

Body:
With the emulator, you set the amount of memory when you start it up, and usually its defaults I believe are far less than you would normally have on your phone.  Even on a regular phone, there are many pitfalls that will cause an outOfMemoryException, e.g. memory leaks (easier than one might think), loading more bitmap data than the resolution / size supports, loading all your images at once, etc.

In general, if you're getting an outOfMemoryException on an actual phone, it tends to be one of the coding errors mentioned above.


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
This is just a general idea and syntax:

```<code>if (cond)
   //do something
else (cond)
   //do something
also (cond)
   //do something
else
   //do something
end
</code>```

ALSO condition is always evaluated. ELSE works as usual.

It works for case too. Probably it is a good way to eliminate break statement:

```<code>case (exp)
   also (const)
      //do something
   else (const)
      //do something
   also (const)
      //do something
   else
      //do something
end
</code>```

can be read as:

```<code>switch (exp)
   case (const)
      //do something
   case (const)
      //do something
      break
   case (const)
      //do something
   default
      //do something
end
</code>```

I don't know if this is useful or simple to read but it's an example.

Body:
This is just a general idea and syntax:

if (cond)
   //do something
else (cond)
   //do something
also (cond)
   //do something
else
   //do something
end

ALSO condition is always evaluated. ELSE works as usual.

It works for case too. Probably it is a good way to eliminate break statement:

case (exp)
   also (const)
      //do something
   else (const)
      //do something
   also (const)
      //do something
   else
      //do something
end

can be read as:

switch (exp)
   case (const)
      //do something
   case (const)
      //do something
      break
   case (const)
      //do something
   default
      //do something
end

I don't know if this is useful or simple to read but it's an example.


问:
How to implement a distributed proxy with quotas?
I'm in the process of developing a scalable proxy (Linux/C/C++, Nginx modules or custom HTTP server) handling incoming HTTP requests, and re-routing them to others locations based on parameters included in the incoming request itself (IP, time for example) or external factors (hence the use of an Nginx module able to retrieve the external factors).

However, the tricky part is regarding quotas. For example, I wish I could block proxying requests originating from an IP when it's daily allowance quota is over.

Implementing quotas is not hard. However, having quotas work in a distributed environment (where ideally everything is shared-nothing) is far from trivial. Indeed, the quota state must be shared to all distributed processes so that they can know whether they should proceed or not. Having a central quota handler means using locks. This makes me think that the performances will drop very quickly. Locking the quotas status every time a proxying request is being handled doesn't look like the solution to me.

Any hints ?

答:
You could give distributed Erlang /OTP a try. You would write your proxy logic in Erlang.

You can maintain your "quotas" in Mnesia tables. Mnesia can be distributed over different Erlang nodes across the network. You can also control wether you need to lock the table while reading or writing.


问:
Are "Stocks" a TDD/Unit testing anti pattern?
From Martin Fowler's Mocks Aren't Stubs he states that Stubs provide canned answers to calls made during the test while Mocks objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

In addition several sources state that Stubs shouldn't fail tests, but Mock could.

So what about this:

```<code>$validator= $this->getMock('ValidatorService');

        // Set up the expectation for the isValid() method
        // to be called only once and with the string 'textToBeValidated'
        // as its parameter and returns true or false.
        $validator->expects($this->once())
                 ->method('isValid')
                 ->with($this->equalTo('textToBeValidated'))
                 ->will($this->returnValue(true));
</code>```

This came up in a code review in a project I'm working on and we called it a Stock (St ub - M ock). Why you ask?!

It set an expectation for isValid() to be called only once and with certain input like a Mock.

It returns a canned answer like a Stub.

I get a feeling that this is wrong, but what if we used a pure Stub only:

```<code> $validator->expects($this->any())  //<-- can't fail the test now
                     ->method('isValid')
                     ->will($this->returnValue(true));   //<-- canned answer
</code>```

I can't verify that the method isValid was called only once with the right parameters.

If the test passed I'm not sure that it passed for the right reason. Maybe isValid() was called twice and that caused it to pass.

So let's use a pure Mock instead:

```<code>$validator->expects($this->once())
                     ->method('isValid')
                     ->with($this->equalTo('textToBeValidated'))
</code>```

I can't verify that my function works correctly, because I only verified that call to isValid() was successful. Maybe there is a bug in the rest of my code using the ValidatorService.

I know some people will talk about state vs behavior verification, but the way I see it the only way to be sure that the test passes for the correct reason is to to use a Stock (i.e. verify the behavior and final state).

Of course the other option is to write 2 test for every test criteria. One using a Mock and an identical test using a Stub. However, that will result in a TestOverflow (a huge number of nearly identical tests).

What is the correct way to have a concrete test of a function using a dependency?

答:
Mocks will return stub answers if that is required by the contract of the class/interface they're mocking. That's just necessary. Your object isn't anything special, it's just a mock.

Nevertheless, prefer stubs to mocks when you can get away with it. Mocks generally lead to less flexible tests compared to tests without mocks. For example, do you have to validate that isValid was called exactly once? Can't you instead have a test case that stubs isValid to return true, another that stubs isValid to return false, and simply observe the results of the two tests? (The answer may be 'no' if you have to make sure the correct text is passed. It's just something to think about.)


答:
Constants have a nasty habit of not remaining constant, especially over long periods of time.

If you go down the constants route, then some development tools will extract the "constant" value at compile time and bury that value into whatever code module they're building.
Efficient?  Yes.  But, if you later decide that you have to change that "constant" to some other value, then those "early-bound" application will get broken.  Your new code will recognise the new value, but those other components will still be passing the old one.

If you go down the public properties route, then every application will come to your component at run-time to acquire the value and so will always get the right one (unless they've inconveniently written it away into some external data store, of course).  Guard against that by not reusing the same underlying values - if you used values 0 .. 3 initially, then don't use any of these values after your refactoring.

Regards,
   Phill  W.

Title: Constants vs public properties for configuration

Body:
My application has a few high level configuration options such as directories which will be used for various things, database connection information and a few other settings which are required for the application to run.

I'm debating with myself whether or not constants are better than variables for this purpose and would like some input.

By having:

```<code> $config = new Config;
 new Whatever($config->foo, $config->bar);
</code>```

Instead of:

```<code>new Whatever(Config::FOO, Config::BAR);
</code>```

I get the power of polymorphism, I can quickly swap between configuration settings by instantiating $config as a different class with the same class members.

There's obviously a trade-off here. Anything which needs the config options must instantiate a $config object, using memory and creating extra code as well as making it so the config options are no long immutable.

The immutability problem could by solved with a method e.g. $config->get('Foo'); so that is potentially a non-issue, although it does add to verbosity and a method call is more expensive than reading a constant or variable.


问:
What's the best RESTful URL structure for a recursive resource?
I'm creating a RESTfull service for a tree-like resource structure and was wondering what the best URL structure would be?

I have three requirements:

be able to get a collection of root
resources

be able to get an
individual resource

be able to get a
collection of child resources

My current thought is:

```<code>/rest/documents
/rest/documents/{id}
/rest/documents/{id}/documents
</code>```

I was also thinking of going the singular / plural routes to denote lists or individual elements, but I know I'm going to have a resource that is the same plural as it is singular, so decided against this.

Does anybody have any thoughts on the above? or have a different / better way of structuring this?

答:
Something like this perhaps:

```<code>/rest/{rootEntity}/Item/{leafEntity}/{id}
/rest/{entity}/ItemList
/rest/{entity}/ItemList/{leafEntity}
</code>```

where {rootEntity} is the starting point of your collection, {leafEntity} is any named leaf node within your tree.

You could append a few parameters any of the above to select, say, Latest or All or something.

Body:
Something like this perhaps:

/rest/{rootEntity}/Item/{leafEntity}/{id}
/rest/{entity}/ItemList
/rest/{entity}/ItemList/{leafEntity}

where {rootEntity} is the starting point of your collection, {leafEntity} is any named leaf node within your tree.

You could append a few parameters any of the above to select, say, Latest or All or something.


问:
Web design pattern
I am building a small website, in PHP and I am using MVC design pattern for the UI.

In the future I will need to add mobile support for my website. It will be in the sub domain "m" like everyone.

All the web is new for me, and I am new with MVC too. I did for each page View, Model and Controller. The Views and the Models are in some internal directory, and the controller is in the public directory of the server (the servers root directory).

My Questions:

Do I need to create a new MVC design for the mobile pages, or can I use the Model of the regular website?

Most of sites have "m" sub-domain for mobile web pages. But the only thing that need to change is the View part. If the public page is the Controller, why not to create only Views for the mobile pages, and the Controller will decide which View will present? Like:

```<code>if ($isMobile) {
    include 'mobiles\main.php';
} else {
    include 'web\main.php';
}
</code>```

With the "m" sub-domain, you must have different Controller. Not so?

答:
My recommendation for this, if you consider both desktop and mobile browsers to be first class citizens, then I would just have separate views for mobile and desktop, while the models and controllers are shared between the two.

Alternatively, you could use one set of views and use responsive design to account for the different devices, but personally I find this to be much more difficult and imposes more constraints on each device.

Title: Web design pattern


问:
How do I create single object that changes functionality based on programmer input?
I have several classes that all behave according to one interface.  But in each class there are additional functions defined that give each class slightly different behavior.  What I want to do is have th programmer using this API to simply  create one instance based on some parameter which generates the correct class type.   And then he/she would only see the methods available to that type while programming

So for example

My interface

```<code>interface IChange
{
    string Change(string inputString);
}
</code>```

And say I have two classes that implement this interface

```<code>class Changer1 : IChange
{

  public string Change(string input){

  ...
  }

  public void DoSomethingSpecial1(){

  ///code that does something specific to Changer1 class
  }

}

class Changer2 : IChange{

  public string Change(string input){

  ...
  }

  public void DoSomethingSpecial2(){

  ///code that does something specific to Changer2 class
  }

}
</code>```

Then I would have a wrapper that sets the appropriate Changer based on an enumeration or some other user input.

```<code>public enum ChangerType
{
    Type1,
    Type2
}

class MasterObject{

        public MasterObject(ChangerType type)
        {
            if (type == ChangerType.Type1)
                SetChanger(new Changer1());
            if (type == ChangerType.Type2)
                SetChanger(new Changer2());
        }

        private IChange _change;

        private void SetChanger(IChange change)
        {
            this._change = change;
        }

}
</code>```

Then as a user of this, in my main program I want to do something like the following where the user creates the main object but it gets created in such a way that they only have access to the appropriate functions.  I.e.  Have available only DoSomethingSpecial1 or only DoSomethingSpecial2 based on the type you created.

```<code>class Program
{
    static void Main(string[] args)
    {
        MasterObject obj1 = new MasterObject(ChangerType.Type1);
        obj1.DoSomethingSpecial1();
        string result1 = obj1.Change("test");

        /// OR

        MasterObject obj2 = new MasterObject(ChangerType.Type2);
        obj2.DoSomethingSpecial2();
        string result2 = obj2.Change("test");

    }

}
</code>```

I have a feeling this is Factory type pattern or maybe Abstract factory, but I'm not sure how to fix my code to implement it correctly.

答: Is there a reason why the "some parameter" that the programmer using the API has to supply can not be the name of the class. They could instantiate an object of Changer1 or Changer2. They are only going to have to remember a third "MasterObject" class name and the parameter "Type1" and "Type2" anyway. And any methods that require you to pass in a parameter of either object can use the interface class. </p>


问:
Is pattern-matching against types idiomatic or poor design?
It seems like F# code often pattern matches against types. Certainly

```<code>match opt with
| Some val -> Something(val)
| None -> Different()
</code>```

seems common.

But from an OOP perspective, that looks an awful lot like control-flow based on a runtime type check, which would typically be frowned on. To spell it out, in OOP you'd probably prefer to use overloading:

```<code>type T =
    abstract member Route : unit -> unit

type Foo() =
    interface T with
        member this.Route() = printfn "Go left"

type Bar() =
    interface T with
        member this.Route() = printfn "Go right"
</code>```

This is certainly more code. OTOH, it seems to my OOP-y mind to have structural advantages:

extension to a new form of T is easy;

I don't have to worry about finding duplication of the route-choosing control flow; and

route choice is immutable in the sense that once I have a Foo in hand, I need never worry about Bar.Route()'s implementation

Are there advantages to pattern-matching against types that I'm not seeing? Is it considered idiomatic or is it a capability that is not commonly used?

答:
F# pattern matching is typically done with a discriminated union rather than with classes (and thus isn't technically a type-check at all).  This allows the compiler to give you a warning when you have unaccounted for cases in a pattern-match.

Another thing to note is that in a functional style, you organize things by functionality rather than by data, so pattern matches allow you to gather the different functionality into one place rather than scattered across classes.  This also has the advantage that you can see how other cases are handled right next to where you need to make your changes.

Adding a new option then looks like:

Add a new option to your discriminated union

Fix all of the warnings on incomplete pattern matches

OwnerDisplayName: Larry OBrien


答:
You are correct in that OOP class hierarchies are very closely related to discriminated unions in F# and that pattern matching is very closely related to dynamic type tests. In fact, this is actually how F# compiles discriminated unions to .NET!

Regarding extensibility, there are two sides of the problem:

OO lets you add new sub-classes, but makes it hard to add new (virtual) functions

FP lets you add new functions, but makes it hard to add new union cases

That said, F# will give you a warning when you miss a case in pattern matching, so adding new union cases is actually not that bad.

Regarding finding duplications in root choosing - F# will give you a warning when you have a match that is duplicate, e.g.:

```<code>match x with
| Some foo -> printfn "first"
| Some foo -> printfn "second" // Warning on this line as it cannot be matched
| None -> printfn "third"
</code>```

The fact that "route choice is immutable" might also be problematic. For example, if you wanted to share the implementation of a function between Foo and Bar cases, but do something else for the Zoo case, you can encode that easily using pattern matching:

```<code>match x with
| Foo y | Bar y -> y * 20
| Zoo y -> y * 30
</code>```

In general, FP is more focused on first designing the types and then adding functions. So it really benefits from the fact that you can fit your types (domain model) in a couple of lines in a single file and then easily add the functions that operate on the domain model.

The two approaches - OO and FP are quite complementary and both have advantages and disadvantages. The tricky thing (coming from the OO perspective) is that F# usually uses the FP style as the default. But if there really is more need for adding new sub-classes, you can always use interfaces. But in most systems, you equally need to add types and functions, so the choice really does not matter that much - and using discriminated unions in F# is nicer.

I'd recommend this great blog series for more information.

Title: Is pattern-matching against types idiomatic or poor design?

Body:
It seems like F# code often pattern matches against types. Certainly

```<code>match opt with
| Some val -> Something(val)
| None -> Different()
</code>```

seems common.

But from an OOP perspective, that looks an awful lot like control-flow based on a runtime type check, which would typically be frowned on. To spell it out, in OOP you'd probably prefer to use overloading:

```<code>type T =
    abstract member Route : unit -> unit

type Foo() =
    interface T with
        member this.Route() = printfn "Go left"

type Bar() =
    interface T with
        member this.Route() = printfn "Go right"
</code>```

This is certainly more code. OTOH, it seems to my OOP-y mind to have structural advantages:

extension to a new form of T is easy;

I don't have to worry about finding duplication of the route-choosing control flow; and

route choice is immutable in the sense that once I have a Foo in hand, I need never worry about Bar.Route()'s implementation

Are there advantages to pattern-matching against types that I'm not seeing? Is it considered idiomatic or is it a capability that is not commonly used?

Body:
You are correct in that OOP class hierarchies are very closely related to discriminated unions in F# and that pattern matching is very closely related to dynamic type tests. In fact, this is actually how F# compiles discriminated unions to .NET!

Regarding extensibility, there are two sides of the problem:

OO lets you add new sub-classes, but makes it hard to add new (virtual) functions

FP lets you add new functions, but makes it hard to add new union cases

That said, F# will give you a warning when you miss a case in pattern matching, so adding new union cases is actually not that bad.

Regarding finding duplications in root choosing - F# will give you a warning when you have a match that is duplicate, e.g.:

match x with
| Some foo -> printfn "first"
| Some foo -> printfn "second" // Warning on this line as it cannot be matched
| None -> printfn "third"

The fact that "route choice is immutable" might also be problematic. For example, if you wanted to share the implementation of a function between Foo and Bar cases, but do something else for the Zoo case, you can encode that easily using pattern matching:

match x with
| Foo y | Bar y -> y * 20
| Zoo y -> y * 30

In general, FP is more focused on first designing the types and then adding functions. So it really benefits from the fact that you can fit your types (domain model) in a couple of lines in a single file and then easily add the functions that operate on the domain model.

The two approaches - OO and FP are quite complementary and both have advantages and disadvantages. The tricky thing (coming from the OO perspective) is that F# usually uses the FP style as the default. But if there really is more need for adding new sub-classes, you can always use interfaces. But in most systems, you equally need to add types and functions, so the choice really does not matter that much - and using discriminated unions in F# is nicer.

I'd recommend this great blog series for more information.


答:
You have correctly observed that pattern matching (essentially a supercharged switch statement) and dynamic dispatch have similarities. They also coexist in some languages, with a  very enjoyable result. However, there are slight differences.

I might use the type system to define a type that can only have a fixed number of subtypes:

```<code>// pseudocode
data Bool = False | True
data Option a = None | Some item:a
data Tree a = Leaf item:a | Node (left:Tree a) (right:Tree a)
</code>```

There will never be another subtype of Bool or Option, so subclassing does not appear to be useful (some languages like Scala have a notion of subclassing that can handle this – a class can be marked as “final“ outside of the current compilation unit, but subtypes can be defined inside this compilation unit).

Because the subtypes of a type like Option are now statically known, the compiler can warn if we forget to handle a case in our pattern match. This means that a pattern match is more like a special downcast that forces us to handle all options.

Furthermore, dynamic method dispatch (which is required for OOP) also implies a runtime type check, but of a different kind. It is therefore fairly irrelevant if we do this type check explicitly through a pattern match or implicitly through a method call.

Body:
You have correctly observed that pattern matching (essentially a supercharged switch statement) and dynamic dispatch have similarities. They also coexist in some languages, with a  very enjoyable result. However, there are slight differences.

I might use the type system to define a type that can only have a fixed number of subtypes:

// pseudocode
data Bool = False | True
data Option a = None | Some item:a
data Tree a = Leaf item:a | Node (left:Tree a) (right:Tree a)

There will never be another subtype of Bool or Option, so subclassing does not appear to be useful (some languages like Scala have a notion of subclassing that can handle this – a class can be marked as “final“ outside of the current compilation unit, but subtypes can be defined inside this compilation unit).

Because the subtypes of a type like Option are now statically known, the compiler can warn if we forget to handle a case in our pattern match. This means that a pattern match is more like a special downcast that forces us to handle all options.

Furthermore, dynamic method dispatch (which is required for OOP) also implies a runtime type check, but of a different kind. It is therefore fairly irrelevant if we do this type check explicitly through a pattern match or implicitly through a method call.


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

答:
2 myths I want to have revealed. A lot of my friends do not understand that Java and JavaScript are completely different, and a lot of non-programmers I know don't understand that there is more than one language. One of my friends was just getting into programming and needed some help from me, 'course he didn't even know what language he was working in.

Those both come up a lot for me.

OwnerDisplayName: Doug


问:
Handling internal IT issues
In the company I work at, developers also serve as internal tech support. This means we have to do three types of things:

Development: writing actual code to implement new features and new products

Maintenance: handle bugs and minor changes with existing customer-facing software

Tech support: handle internal issues other employees have e.g. locked out of AD, network drive is missing, internet is down, new software installation, need permissions changes, etc.

The tech support aspect of my job is the most troubling right now. This is because:

someone with a problem will likely interrupt you immediately, taking you away from development

problems come in too many ways: email, google chat, phone call, post-it notes on your desk, etc.

people often cannot or do not determine the severity or scope of their problem before asking for help, i.e. simple problems that inconvenience one person might come in the same way -- and often with the same urgency -- as major customer-facing issues that could affect thousands

My question is: What are the proven methods for dealing with internal IT issues?

Should we use software designed for this purpose? If so, how should it be separated from any software used for customer-facing issues or bug tracking software? How can the IT/development department ensure it's used properly?

Also, is it a problem that developers handle these internal problems in the first place? Would it be ideal to have a separate person or department to handle these types of problems?

答:
If your development people are fielding IT questions, and it's taking a reasonable amount of time away from development it's hurting your companies bottom line, period.  It should be an easy sell to hire a part-time or full-time IT/admin:

Figure out how much time each developer is spending on IT

This is the base IT personel cost of the company

This also tells you how much time/productivity is lost towards developing profit producing widgets.

Take this to management, it should be easy to convince them a dedicated IT guy may increase profit due to reduced developer downtime (better bug fix and feature release turnaround)

As for the software aspect, set up guidelines for initiating an IT request:

Submit queries via a ticketing system (most CRM systems have this, and there are quite a few free solutions)

CRM Solution

Zendesk (or some equivalent)

Trello

OR

Submit via email (a gtalk request shouldn't cut it, there has to be some sort of trackability)

If this is the method, an internal address (ie. it@example.com) should be made to field these, and the appropriate emails added to this distro group, that way each IT person/dev doesn't get specific questions, but can be handled by whomever has some free-time.

If they initiate the convo via messaging (or anything outside your "tracking" system), have them submit a formal request through whatever system is devised.

The most important part of this is that you/your IT people (once hired) need to stick to their method and not let it slip, it'll streamline the entire process in the long run and not let things slip through the cracks.

Title: Handling internal IT issues


问:
Can I remove a company's logo from a software licensed under Mozilla Public License Version 1.1?
I have tried looking for an answer to this question, but I couldn't find anything related.

To put it in a nutshell, I want to fork the existing Komodo Edit project, which is licensed under MPL Version 1.1, and create a new derived project/software. I would like to remove certain features from the current project, including ActiveState's logo, but I do not understand the technical jargon on the license. Also, I plan to keep the derived project completely free and open-source.

I'd be really grateful, if someone could explain it to me.

Here is the link to the license : https://github.com/Komodo/KomodoEdit/blob/trunk/LICENSE.txt

答:
The license allows you to create a fork, if you follow the rules that can be summarized as

Your fork must use the same license

You must state clearly and prominently that your fork is derived from KomodoEdit

The project did not contain any explicit text regarding the use of ActiveState's logo (at least not in the obvious places where I looked), but according to Komodo Edit's website, the names Komodo and ActiveState are trademarks, so it is likely that the logo is a trademark as well.

As the logo (likely) and name are trademarked, you can not use them in your fork without a separate explicit permission from ActiveState. (mentioning that your fork is derived from KomodoEdit doesn't count as 'use' in this sense, but you should acknowledge that those names are trademarks)


答:
Should we use software designed for this purpose? If so, how should it
  be separated from any software used for customer-facing issues or bug
  tracking software?

I don't see why not and I don't think it should be separate. It's more complicated to track different systems. Personally, I like systems that integrate with email. This way I can control all my "pop ups" and not have to manage too many apps at the same time. If the email contains a link to get right where I need to be for a specific matter, the better.

How can the IT/development department ensure it's
  used properly?

Like anything else, you have to define what "proper" means. Then it comes down to training, administration, and accountability. You're probably going to need buy-in from high up in the company if you want to be able to enforce its usage. There are a lot of bad habits you need to break here.

Also, is it a problem that developers handle these internal problems
  in the first place? Would it be ideal to have a separate person or
  department to handle these types of problems?

I don't know what is ideal. From a programmer's perspective, most do not want to deal with customers. The main reason is being interrupted. You can get around this if all the devs are "on call" for different periods of the day. If I know I have an uninterrupted block of a few hours, I'll make sure I spend that time on a programming project problem that I can fit in if possible.

There are some companies that make customer service so important, they make everyone do it for at least a period of time as part of their training. It can give insight on how the app is used. Releasing a known bug may get a second thought if you don't want those phone calls.

Someone running the company has to decide what is important and where do they want to make the trade-offs. Developers are expensive and they lose money every time a dev is interrupted. Support staff tend to make less money also. Not everyone is good at customer support or programming, so there are even fewer who are good at both. Depending on the current status of my team or the need to hire more programmers or replacements, I may think twice about this additional burden. If two jobs are equal in all ways except one requires doing tech support, it could be difficult to find good programmers because they'll take the other option. A company has to be really good in other ways to attract talent when the required duties are less than desirable to some.

Title: Handling internal IT issues

Body:
In the company I work at, developers also serve as internal tech support. This means we have to do three types of things:

Development: writing actual code to implement new features and new products

Maintenance: handle bugs and minor changes with existing customer-facing software

Tech support: handle internal issues other employees have e.g. locked out of AD, network drive is missing, internet is down, new software installation, need permissions changes, etc.

The tech support aspect of my job is the most troubling right now. This is because:

someone with a problem will likely interrupt you immediately, taking you away from development

problems come in too many ways: email, google chat, phone call, post-it notes on your desk, etc.

people often cannot or do not determine the severity or scope of their problem before asking for help, i.e. simple problems that inconvenience one person might come in the same way -- and often with the same urgency -- as major customer-facing issues that could affect thousands

My question is: What are the proven methods for dealing with internal IT issues?

Should we use software designed for this purpose? If so, how should it be separated from any software used for customer-facing issues or bug tracking software? How can the IT/development department ensure it's used properly?

Also, is it a problem that developers handle these internal problems in the first place? Would it be ideal to have a separate person or department to handle these types of problems?


答:
Partially, you see it more often in functional programming because you use types to make decisions more often.  I realize you probably just chose examples more or less at random, but the OOP equivalent to your pattern matching example would more often look like:

```<code>if (opt != null)
    opt.Something()
else
    Different()
</code>```

In other words, it's relatively rare to use polymorphism to avoid routine things like null checks in OOP.  Just like an OO programmer doesn't create a null object in every little situation, a functional programmer doesn't always overload a function, especially when you know your list of patterns is guaranteed to be exhaustive.  If you use the type system in more situations, you're going to see it used in ways you are not accustomed to.

Conversely, the idiomatic functional programming equivalent to your OOP example would most likely not use pattern matching, but would have fooRoute and barRoute functions that would get passed as arguments to the calling code.  If someone used pattern matching in that situation, it would usually be considered wrong, just like someone switching on types would be considered wrong in OOP.

So when is pattern matching considered good functional programming code?  When you're doing more than just looking at the types, and when extending the requirements won't require adding more cases.  For example, Some val doesn't merely check that opt has type Some, it also binds val to the underlying type for type-safe use on the other side of the ->.  You know you'll most likely never have a need for a third case, so it's a good use.

Pattern matching may superficially resemble an object-oriented switch statement, but there is a lot more going on, especially with longer or nested patterns.  Make sure you take everything it's doing into account before declaring it equivalent to some poorly-designed OOP code.  Often, it is succinctly handling a situation that is not able to be cleanly represented in an inheritance hierarchy.

Body:
Partially, you see it more often in functional programming because you use types to make decisions more often.  I realize you probably just chose examples more or less at random, but the OOP equivalent to your pattern matching example would more often look like:

if (opt != null)
    opt.Something()
else
    Different()

In other words, it's relatively rare to use polymorphism to avoid routine things like null checks in OOP.  Just like an OO programmer doesn't create a null object in every little situation, a functional programmer doesn't always overload a function, especially when you know your list of patterns is guaranteed to be exhaustive.  If you use the type system in more situations, you're going to see it used in ways you are not accustomed to.

Conversely, the idiomatic functional programming equivalent to your OOP example would most likely not use pattern matching, but would have fooRoute and barRoute functions that would get passed as arguments to the calling code.  If someone used pattern matching in that situation, it would usually be considered wrong, just like someone switching on types would be considered wrong in OOP.

So when is pattern matching considered good functional programming code?  When you're doing more than just looking at the types, and when extending the requirements won't require adding more cases.  For example, Some val doesn't merely check that opt has type Some, it also binds val to the underlying type for type-safe use on the other side of the ->.  You know you'll most likely never have a need for a third case, so it's a good use.

Pattern matching may superficially resemble an object-oriented switch statement, but there is a lot more going on, especially with longer or nested patterns.  Make sure you take everything it's doing into account before declaring it equivalent to some poorly-designed OOP code.  Often, it is succinctly handling a situation that is not able to be cleanly represented in an inheritance hierarchy.


问:
So I'm a developing a workflow with vagrant+git...does this make sense?
Relevant Background Details

We've got two types of VMs (Utility Boxes & Web Servers) that developers need.

We are going to be using git for version control.

We have developers who have different preferences for their working environment (e.g. Some Linux, Some Windows).

I'm in the Linux camp and I believe Git and Windows doesn't mix as well as Linux & Git. However, this could be personal bias.

We using Linux in production.

Building the Vagrant VMs for distribution

Build a base box with the relevant OS for vagrant.

Using a configuration manager (e.g. Chef) to build out the Utility & Web images, convert them to new base boxes. It will clone service configurations from a centralized git repository.

Distribute the base boxes (really just virtual machine images) for the users to develop locally with vagrant. The distributed box will automatically pull in source code from certain git repos (e.g. libraries).

If changes are planned for the production environment, all developers will need to pull down new base boxes for vagrant as they come prepackaged. I think this is the simplest way for a new developer to deal with it. Staging is updated to match the new development VMs in preparation.

Developer Workflow

Get assigned an issue from the issue tracker.

Use the vagrant VM to clone the current dev repository into the folder it shares with the host OS (so the Developer can use their favorite IDE).

Developer commits changes and tests locally.

When satisfied, Developer merges his changes to the dev repository. If conflicts, work with the Developer commited the conflicting code to resolve the issue.

When Dev is in a stable state, Dev is merged with the current Staging repository for QA of the new features. Nothing is pushed from Dev to Staging until Step #6 is completed. Hooks generate new copy of documentation for Staging.

Staging is cloned into Production once the QA is completed. Hooks generate new copy of documentation for Production.

Is there any obvious flaws/pitfalls in the above or steps that are generally considered 'best practices' that should be added?

答:
Your plan sounds great! I think you are off to a really good start.

My only advice is in regard to you Developer Workflow. I think you're dev branch may become problematic, because developers will be merging code willy-nilly then they think its ready.

If both branchA and branchB, C, and D are merged into dev, and it fails, you can't be certain which parts are necessarily failing. Also, if someone pushes up something with a conflict, you dont know who it was. Madness and insanity are bound to ensue.

If a feature turns out not to be ready, and code needs to be backed out of dev, other developers will have already pulled down their additions. Those developers then will merge back into dev, unwittingly re-introducing the broken code. Madness and insanity are bound to ensue.

You're going to need a couple steps of separation to keep untested code away from tested code.

This all depends on the skill sets of your team, and how you actually work together. What follows is my solution to problems of a quickly expanding team with differing levels of git knowledge and different levels of developers code dependability.

I always try to tell people to not simply think about developer workflow, but testing procedure, and release process. They all need to be planned as part of a singular process.

Lead Dev or Release Mngr (whoever) creates a new release branch based off master. This branch will be a container for anything going on it in the next release.

Lead/ReleaseMngr creates integration branch based off release.

Developer creates new feature branch (or topic branch, whatever you want to call it), based off the current release branch.

Developer tests locally, is happy.

The developers feature branch  deployed somewhere and tested by QA independently of any untested code.

QA signs off on feature - it gets merged into an integration branch. (ideally, IMHO, only after the feature branch has been rebased off release, to force the conflict resolutions )

QA tests the integration branch which is just the release branch + this one feature.

QA signs off - integration is merged into release (if not signed off, integration is blown away and recreated based on release). This is the reason for integration. No one pulls form this branch, and it can be blown away as needed.

Now the feature is in release, and can be shared with other developers making features based off release branch.

Release is good, merge to master. Deploy, make a new release branch based off master.

I know it sounds like a lot, but it really will save you from the headaches and, in my experience, are inevitable with large projects with logs of people having differing levels of knowledge.

If you have a small team with a simple release process, or a team that is very experienced - all this may not be necessary - but do be aware of the inherent problem with testing multiple people's code at the same time in your dev branch.

All that said, its my understanding the GitHub team just lets everyone merge into master directly (after a brief code review) and auto deploys ~30 times a day.


问:
Do you have to rename the software when you fork a repo?
I forked a repo some time ago and created a few pull requests which went unanswered.

Now, the software is MIT-licensed, and I kept the copyright notice there.

Do I have to rename the software, or whoever forks a repo can keep referring to it by the same name?

Thanks!

答:
Forking a git repo is not the same necessarily as forking a project for release.

The rules around naming and code reuse are more a matter of that projects particular licence. In git, a fork just means you have a copy of their code in your own remote repository, it says nothing about the licensing or how/if you can release your own version of the project.

We use forks at work - each developer works off a fork of the main repo. Has nothing to do with releasing different versions. It just keeps the main repo clean, and avoids the need to setup rules about who can push to which branches, because each developer owns their own remote copy.