问:
Determinining "value" in multi-agent microeconomical simulation
I am trying to determine an objective way for a self-interested agent to calculate the optimal buying/selling price for goods in a multi-agent simulation not dissimilar to Sugarscape (http://en.wikipedia.org/wiki/Sugarscape). The simulation is as follows:

Each agent has a stock of food F, a stock of money G, a certain amount of "energy", E, and a position (x, y) on a square grid. Moving from one square to a neighboring square expends A units of energy, and energy is naturally expended at a rate of B units per simulation day. An agent has the following options available to it during each day: consume a unit of food to increase its energy by Q units; move to another location (provided it has sufficient energy), "forage" for food (expend P units of energy to obtain a [possibly unknown] quantity of food), or trade with a neighboring agent for a mutually-agreeable price.

Each agent's goal is to maximize its "utility function" U(E, F, G) without regard for that of other agents.

Right away, this seems to give a base "use value" of food: Vuse = U(E + Q, F - 1, G) - U(E, F, G), but if this was the whole story, this wouldn't be an interesting problem.

It seems the most general (but exponential-time) solution would look something like this:

```<code>Function SearchActions(State S):
    Add(consume food) to action set
    Add(forage for food) to action set
    For each other agent A
        For each possible trading price P
            Add(trade with A at price P) to action set
    For each action X in action set
        S' = Apply X to S
        SearchActions(S')
    Return optimal X
End function
</code>```

However, the major difficulty gets swept under the rug by "for each possible price", because the price that agent A will buy/sell for is itself dependent on an identical calculation...e.g.

My calculation of the value depends on either what I can get from using it myself, or what someone else will pay for it...but what they will pay for it depends on what I will pay for it.

How do you cut this knot?

I know this problem has been solved before...but I cannot find any references to it, let alone any actual implementations. The closest I've come has been a paper about "Strategic Planning" in SugarScape, but it only seems to give the results of the planning, rather than explaining how the planning is done.

答:
The key to this is each agent's cost of mining. Presumably, at any given time, some agents will be closer to a food mine than others.

The cost of mining is energy + time. An agent further away from a mine will thus have a higher cost because it will have to use more energy and time to travel there.

Each agent will need to determine its maximum buying price based on its own current cost of mining and its current stock of energy, food, and money. Conversely, each agent will need to determine its minimum selling price based on those same four factors.

A trade happens when one agent's buying price is higher than another agent's selling price.

How do you set the prices then? The same way we humans do. An agent trying to sell will offer at a price higher than its minimum selling price. An agent trying to buy will propose a purchase at a lower price than its minimum buying price. The two will then negotiate until (or if) a price is reached that is agreeable to both.


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

答:
You are doing Factory pattern here with "MasterObject".  However, if it is the correct way depends on how this is used.  Generally, with the Factory class your user is providing some information and the code is selecting the correct class to use to represent the information.  You are very close on this point.  However, your MasterObject is wrong in that it is storing the implementing class in itself and returning itself.  Generally, the factory is only to receive arguments and then select the best object class to return to you.  In your case the object you should be getting back is Changer1 or Changer2.  I noticed that you are handling the object type correctly using the interface name as the type.

Now, you have a instance of Changer1 or Changer2, which implements the common interface which is good, along with supporting methods that are unique to the class (such as the example of classic "bark" or "wag_tail" methods).

ContentLicense: CC BY-SA 3.0


问:
In an event-driven environment, how should a "cancel" function abort all further events?
In my iOS app, things are mostly driven by events.

The user presses a button

The app listens for an external device to be connected to the iOS device

Once the device is detected (is connected), an asynchronous call is made to a web service (to check for user authenticity)

The web service returns the user's authenticity (such as a boolean)

Another asynchronous web service is called for a stage 2 authenticity

Result is returned

My question is: If I give the user a dialog box saying "Please wait, processing" and I give them a "Cancel" button, how should I (or how might I) abort everything that's happening?

One way to do this is to simply have a boolean called "userDidCancelEverything" and every event-driven method checks to see if this is true. This seems ugly though.

答:
I known, this is an old question, but interestingly enough, and there is a nice solution:

Suppose, all those functions were asynchronous. The asynchronous pattern is called a "Continuation".

A possible implementation of such a "continuation" could use dispatch queues and blocks directly, for example:

```<code>dispatch(my_queue, ^{
    [self connectDeviceWithCompletion:^(id result){
        if (result) {
            [self authenticateWithCompletion:^(id result){
                 if (result) {
                     [self performTwoFactorAuthWithCompletion:^(id result) {
                         if (result) {
                              ...
                         }
                     }];
                 }
            }];
        }
    }];
});
</code>```

As you can see, "continuation" with dispatch and blocks becomes quickly confusing, and I didn't even add error checking, and cancellation.

Note, that canceling a block which has been enqueued isn't that easily possible.

A more comprehensible solution that also supports error handling and cancellation can be achieved using a concept called "Promise" (see wiki Futures and promises]. Promises are very popular in JavaScript and other languages, but there are a few Objective-C libraries which implement Promises, see this answer:
success:/failure: blocks vs completion: block.

Utilizing the RXPromise library one could write:

```<code>RXPromise* finalResult = [self connectDevice]
.then(^(id result){
    // device successfully connected with result
    return [self authenticate];
}, nil)
.then(^id(id result){
    // authenticated successfully with result
    return [self performTwoFactorAuth];
}, nil)
.then(^id(id result){
    // successfully performed two-factor-authentication
    // do something
    ...
}, nil)

[finalResult setTimeout:5*60]; // we cancel everything after 5 minutes

// Catch any error:
finalResult.then(nil, id(NSError* error){
    NSLog(@"Something went wrong, or user cancelled with error: %@", error);
});

self.finalResultPromise = finalResult;
...
</code>```

Later:

Suppose, the user waits for an result to happen eventually. When navigating back from the current view, this shall cancel all the asynchronous operations:

```<code>- (void) viewDidDisappear:(BOOL)animated {
    // we are no longer interested in the result
    [self.finalResultPromise cancel];
    self.finalResultPromise = nil;

    [super viewDidDisappear:animated];
}
</code>```

Disclosure: I'm the author of RXPromsie ;)

Body:
I known, this is an old question, but interestingly enough, and there is a nice solution:

Suppose, all those functions were asynchronous. The asynchronous pattern is called a "Continuation".

A possible implementation of such a "continuation" could use dispatch queues and blocks directly, for example:

dispatch(my_queue, ^{
    [self connectDeviceWithCompletion:^(id result){
        if (result) {
            [self authenticateWithCompletion:^(id result){
                 if (result) {
                     [self performTwoFactorAuthWithCompletion:^(id result) {
                         if (result) {
                              ...
                         }
                     }];
                 }
            }];
        }
    }];
});

As you can see, "continuation" with dispatch and blocks becomes quickly confusing, and I didn't even add error checking, and cancellation.

Note, that canceling a block which has been enqueued isn't that easily possible.

A more comprehensible solution that also supports error handling and cancellation can be achieved using a concept called "Promise" (see wiki Futures and promises]. Promises are very popular in JavaScript and other languages, but there are a few Objective-C libraries which implement Promises, see this answer:
success:/failure: blocks vs completion: block.

Utilizing the RXPromise library one could write:

RXPromise* finalResult = [self connectDevice]
.then(^(id result){
    // device successfully connected with result
    return [self authenticate];
}, nil)
.then(^id(id result){
    // authenticated successfully with result
    return [self performTwoFactorAuth];
}, nil)
.then(^id(id result){
    // successfully performed two-factor-authentication
    // do something
    ...
}, nil)

[finalResult setTimeout:5*60]; // we cancel everything after 5 minutes

// Catch any error:
finalResult.then(nil, id(NSError* error){
    NSLog(@"Something went wrong, or user cancelled with error: %@", error);
});

self.finalResultPromise = finalResult;
...

Later:

Suppose, the user waits for an result to happen eventually. When navigating back from the current view, this shall cancel all the asynchronous operations:

- (void) viewDidDisappear:(BOOL)animated {
    // we are no longer interested in the result
    [self.finalResultPromise cancel];
    self.finalResultPromise = nil;

    [super viewDidDisappear:animated];
}

Disclosure: I'm the author of RXPromsie ;)


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

答:
Throwing exceptions early in general is a good practice because you don't want broken contracts to flow through the code further than necessary. For example, if you expect a certain function parameter to be a positive integer then you should enforce that constraint at the point of the function call instead of waiting until that variable is used somewhere else in the code stack.

Catching late I can't really comment on because I have my own rules and it changes from project to project. The one thing I try to do though is separate the exceptions into two groups. One is for internal use only and the other is for external use only. Internal exception are caught and handled by my own code and external exception are meant to be handled by whatever code is calling me. This is basically a form of catching things later but not quite because it offers me the flexibility to deviate from the rule when necessary in the internal code.


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

答: The general outline sounds good. The only thing I would change is that the base boxes themselves should be self-updating. Presumably your provisioning scripts also live in git so you could automatically update the boxes by a properly configured /etc/rc.local script. The base box should just have the bare minimum necessary to start and then download all the necessary pieces for configuration. This way you decouple the distribution of the boxes from the actual update process and don't need to ship an entire new base box every time you make changes, excepting OS upgrades of course.


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

答:
It seems like there are two parts to your question:

Getting the data from multiple sources

Transforming the data to the expected format

The task of getting the data from the sources would be handled by the repository.  Part of fetching the data is transforming it to it's expected format.  The question you have to answer is: "What is the expected class?".

If this data is only used as this final singular type, then each repository will return the single type.  A call to MyRepository will internally call each of the Source Repositories.

```<code>public class MyRepository {
  ISourceRepository[] Sources;

  private getFromSources();
  public getData(); //uses getFromSources
}
</code>```

Sometimes the data is useful in it's original form as well as the final type, if this is the case, the repositories should return separate types, which you can then transform to the new type with something like the visitor pattern:

```<code>public class MyDataFormatter {
  public MyData format(SourceOne data);
  public MyData format(SourceTwo data);
  public MyData format(SourceThree data);
}

public class MyDataRepository {
  public IRepository Repos;
  public function getData() {
    get data from each repo in it's original format
    call MyDataFormatter.format(data)
  }
}
</code>```

adapted from this link

Title: Pattern for multiple datasources

Body:
It seems like there are two parts to your question:

Getting the data from multiple sources

Transforming the data to the expected format

The task of getting the data from the sources would be handled by the repository.  Part of fetching the data is transforming it to it's expected format.  The question you have to answer is: "What is the expected class?".

If this data is only used as this final singular type, then each repository will return the single type.  A call to MyRepository will internally call each of the Source Repositories.

public class MyRepository {
  ISourceRepository[] Sources;

  private getFromSources();
  public getData(); //uses getFromSources
}

Sometimes the data is useful in it's original form as well as the final type, if this is the case, the repositories should return separate types, which you can then transform to the new type with something like the visitor pattern:

public class MyDataFormatter {
  public MyData format(SourceOne data);
  public MyData format(SourceTwo data);
  public MyData format(SourceThree data);
}

public class MyDataRepository {
  public IRepository Repos;
  public function getData() {
    get data from each repo in it's original format
    call MyDataFormatter.format(data)
  }
}

adapted from this link


问:
I'm struggling with abstracting my animation code in my game using a functional style. How can I do this?
My game is a top down 2D shmup programmed in a functional style.  I'm struggling with abstracting the code that is responsible for animating the projectiles.  There are many types of guns with many types of projectiles.  Here are a few that are very different:

A standard gun that shoots a bullet that travels a distance over time.

A laser that shoots a line that goes from start to end in an instant.

This is different from the standard gun projectile because its projectile doesn't travel over time.  It's drawn as a line.  Unlike the standard gun, the laser beam animation should last after the projectile hits something.

A psychic shockwave that forms a circular blast wave around your body and damages anything in range.  The size of the circle is variable.

This is different from the standard gun projectile because its size is variable and circular.  Also, it doesn't move.  I'm struggling on how I can use a sprite sheet for this.  It seems like the best way might be to draw a circle on the screen.  All the other projectiles are sprites.

This is different from the laser because it's a circular shape rather than a line.

If this were object oriented, the path I'd take is straight-forward:  I'd create an Animation class that is responsible for animating itself.  The client code would have no idea how the animation occurs, it would just pass in the necessary objects in order to get it done.

But I'm not sure how to do something like this in a functional style.  Right now I represent everything as data.  A projectile contains animation data like so:

```<code>projectile: {
  type: "laser"
  animation: ...
}
</code>```

But what feels very wrong is I have to have one switch to create this projectile, and then in my rendering code, I have to have another switch to decide how to use the data to animate it.  EG:

```<code>if projectile.type is "standard gun"
  rotateBulletTowardsVelocityAndAnimateAtPosition(projectile)
if projectile.type is "laser"
  rotateLaserTowardsTargetAndAnimateFromStartToTarget(projectile)
if projectile.type is "psychic shockwave"
  drawCircleAroundProjectilePosition(projectile)
</code>```

This doesn't seem very abstract to me.  What's a better way to code this while still being functional about it?

答: You could provide a function which supplies the path of the projectile given a time input and origin, and another which accepts the coordinates of the projectile and performs rendering.</p>


问:
How can we calculate Big-O complexity in Functional & Reactive Programming
I started learning functional programming, I am trying to compare between different algorithms that are written in an imperative, functional , parallel programming and using Collections and Lambda expressions.
In order to make my question clear and avoid sharing long algorithms that I am working on. I will take as an example the well-known modified Fibonacci algorithm (Euler Problem 2):

Here is the problem : http://projecteuler.net/problem=2

```<code>//Iterative way:

int result=2;
int first=1;
int second=2;
int i=2;

while (i < 4000000)
{
    i = first + second;

    if (i % 2 == 0)
    {
       result += i;
    }

    first = second;
    second = i;
 }

 Console.WriteLine(result);

// Recursive functional way:
FibonacciTerms(1, 2).TakeWhile(x => (x <= 4000000) )
private static int SumEvenFibonarciTerms()
{
    return FibonacciTerms(1, 2)
            .TakeWhile(x => (x <= 4000000)).Where(x => x % 2 == 0)
            .Sum();
}

//Asynchrounous way
let rec fib x = if x <= 2 then 1 else fib(x-1) + fib(x-2)

let fibs =
    Async.Parallel [ for i in 0..40 -> async { return fib(i) } ]
    |> Async.RunSynchronously
</code>```

How can I calculate the Big-O in algorithms that are written using Lamda expression (Complexity of functions like: filter, where, reduceleft, reducright, .. )

In the functional and Asynchrounous algo, the both are written in the same way ? Should we consider their complexity the same knowing that there is difference in the time of execution ?

答:
Your programming language paradigm may help you to write code in less line or to express yourself in an easier. It won't change complexity of your program. The questions remaining are the same:

What's the worst case ?

How much "unit" operations are require to perform your algorithm ?

This means that you have to mostly understand how your data structures behave and your code by itself.


答:
I think you need to invert your dependencies here - those different animation types can be written as standalone functions that given a location, render an animation in that location (or returns an animation-renderer that will execute at that location that you may execute later).

Once you have implemented these rendering functions, what you need to do is have them passed down through the layers. I would put them into your players state such that they have an active gun, and everytime they switch guns, you get a new player state with the new shooting renderer, that renderer can be handed to whatever needs it when they try and shoot.

Title: I'm struggling with abstracting my animation code in my game using a functional style. How can I do this?

Body:
My game is a top down 2D shmup programmed in a functional style.  I'm struggling with abstracting the code that is responsible for animating the projectiles.  There are many types of guns with many types of projectiles.  Here are a few that are very different:

A standard gun that shoots a bullet that travels a distance over time.

A laser that shoots a line that goes from start to end in an instant.

This is different from the standard gun projectile because its projectile doesn't travel over time.  It's drawn as a line.  Unlike the standard gun, the laser beam animation should last after the projectile hits something.

A psychic shockwave that forms a circular blast wave around your body and damages anything in range.  The size of the circle is variable.

This is different from the standard gun projectile because its size is variable and circular.  Also, it doesn't move.  I'm struggling on how I can use a sprite sheet for this.  It seems like the best way might be to draw a circle on the screen.  All the other projectiles are sprites.

This is different from the laser because it's a circular shape rather than a line.

If this were object oriented, the path I'd take is straight-forward:  I'd create an Animation class that is responsible for animating itself.  The client code would have no idea how the animation occurs, it would just pass in the necessary objects in order to get it done.

But I'm not sure how to do something like this in a functional style.  Right now I represent everything as data.  A projectile contains animation data like so:

```<code>projectile: {
  type: "laser"
  animation: ...
}
</code>```

But what feels very wrong is I have to have one switch to create this projectile, and then in my rendering code, I have to have another switch to decide how to use the data to animate it.  EG:

```<code>if projectile.type is "standard gun"
  rotateBulletTowardsVelocityAndAnimateAtPosition(projectile)
if projectile.type is "laser"
  rotateLaserTowardsTargetAndAnimateFromStartToTarget(projectile)
if projectile.type is "psychic shockwave"
  drawCircleAroundProjectilePosition(projectile)
</code>```

This doesn't seem very abstract to me.  What's a better way to code this while still being functional about it?


问:
When am I justified in using a License?
I recently wrote a little CLI Hangman game in Python; it's not anything huge, but I did write it all myself. I would like to keep the program open and free (GPL ver.3), but it's so small I don't know if I need to/can license it.

Is there a certain point where a program becomes "license-able", or can I license any program I write?

答:
You can (i.e. you are legally permitted) to put a GPL license on any piece of software that you wrote, no matter how trivial it is.

A license only has real meaning with respect to your rights if you are willing to try to enforce it.  That means that you need to track down people who violate your rights, and try to get them to stop, ultimately by taking them to court.  For a sufficiently small program (i.e. trivial), it is simply not worth your effort to do that:

The chances that nobody who matters1 will bother to violate your rights in a way that matters in the first place.  (Your program is trivial, and could therefore be trivially replaced with a program they wrote themselves ... assuming that it was worth using.)

If they did violate, and you discovered this, it would cost you money to sue them.  (Lawyer's fees, court costs, discovery costs, etc, etc.)

There is a significant chance that your lawsuit would be thrown out on "Summary Judgement" ... where the Judge basically decides that you cannot sustain a case on legal grounds.  (For example, that your program doesn't contain the minimal amount of copyrightable content.)

If you do get to a trial, here is a significant chance that you will lose anyway, unless you can convince the judge or jury that your trivial program is worthy of protection.

Even if you win, it is likely that you will only be awarded trivial damages ... leaving your out of pocket for all of the expenses you incurred.

In short, it is not worth suing over a "trivial" program.  (Use your own judgement to decide what is trivial ... in this context.)

So that means that slapping an open source (or closed source) license on a piece of trivial software makes no material difference in terms of protecting your rights.

On the other hand, if your aspirations for your software are altruistic, putting an explicit (open source) license on a piece of software does make it clear to potential users of your software what their rights are.  If you neglect to include a license, some future user may be left in the awkward position of not knowing your intention, and not being able to contact you to ask permission.

I've encountered situations where I wanted to include a worthy bit of code into a larger open source project, only to discover that the author hadn't put an explicit license on it, and either wasn't contactable, or wasn't interested in clarifying the situation by stating what the license was.  Net result - it was too risky to incorporate the code in the project.

(Legally, the default position is that copyrightable material is copyrighted by the author(s) and permission to copy is NOT granted.)

1 - That is, some person, company, organization who has enough resources to be worth suing.  Suing someone with no money means you won't get a payout, and you are liable to be labelled a bully and a copyright troll.

Title: When am I justified in using a License?


答:
If you do not license your code, no matter how small, it is by default protected by Copyright law. This means that, unless it falls into a very small and specific set of use cases, people won't be able to reuse or redistribute your code without your express permission.

You're potentially asking two questions by suggesting a copyleft license such as GPL v3 though, because it implies that you have two intentions:

To provide your code free for use for any purpose, provided that

Redistributions are also offered under a similar license

The first can be satisfied by any open source license, and it's definitely preferable to none, because without any, it is effectively under "all rights reserved". People who don't want to be on the wrong side of the law will see "no license" as a huge red flag and they'll keep clear of your code.

The second has practical problems as Stephen mentioned, since for trivial pieces of code, it is extremely difficult to spot let alone prosecute offenders of your license, i.e. those that redistribute your code without also offering it under a compatible license, so you cannot guarantee that no one will infringe.

Title: When am I justified in using a License?

Body:
I recently wrote a little CLI Hangman game in Python; it's not anything huge, but I did write it all myself. I would like to keep the program open and free (GPL ver.3), but it's so small I don't know if I need to/can license it.

Is there a certain point where a program becomes "license-able", or can I license any program I write?


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

答:
I will presume your workplace is like 99.99% others and management will not give a head count increase in a whim.  You also do not state you are over worked, so my guess is your ideal of a new department is not going to happen any time soon. Just asking for it will get you no where, you will need to show its needed, based on evidence. Without a formal system this evidence will not be available.

The problem is best solved by creating an SLA (Service level Agreement) for tech support calls. Some issues (network down) are more important that others ( Need to install Candy Crush on receptionists computer ).

Reach an agreement with management and users of how quickly you will respond to different request types. After this, reach agreement on how you will be informed of issues - an email to "support@acme.com" is the only software you need. High priority meeting P1's (instant response) is through phone call. Email is checked every couple of hours. Dedicated help desk software can come later, if at all.

Assign one developer to be on it support each week on a rotation. That week support is their priority job, and they are assigned non urgent development work. Other developers are not to provide support (except maybe priority calls covered under the SLA)

The advantage os this system is when you get the dedicated IT guy(s) the same system is used, and it can accurately track how much support is being done - justifying you request for a dedicated team (or not) as the case may be.

Title: Handling internal IT issues


答:
To answer this question properly, let's take a step back and ask an even more fundamental question.

Why is it that we have exceptions in the first place?

We throw exceptions to let the caller of our method know that we couldn't do what we were asked to do.  The type of the exception explains why we couldn't do what we wanted to do.

Let's take a look at some code:

```<code>double MethodA()
{
    return PropertyA - PropertyB.NestedProperty;
}
</code>```

This code can obviously throw a null reference exception if PropertyB is null.  There are two things that we could do in this case to "correct" for this situation.  We could:

Automatically create PropertyB if we don't have it; or

Let the exception bubble up to the calling method.

Creating PropertyB here could be very dangerous.  What reason does this method have to create PropertyB?  Surely this would violate the single responsibility principle.  In all likelihood, if PropertyB does not exist here, it indicates that something has gone wrong.  The method is being called on a partially constructed object or PropertyB was set to null incorrectly.  By creating PropertyB here, we could be hiding a much bigger bug which could bite us later on, such as a bug which causes data corruption.

If, instead, we let the null reference bubble up, we are letting the developer who called this method know, as soon as we can, that something went wrong.  A vital pre-condition of calling this method has been missed.

So in effect, we are throwing early because it separates our concerns much better.  As soon as a fault has occurred, we are letting the upstream developers know about it.

Why we "catch late" is a different story.  We don't really want to catch late, we really want to catch as early as we know how to handle the issue properly.  Some of the time this will be fifteen layers of abstraction later and some of the time this will be at the point of creation.

The point is that we want to catch the exception at the layer of abstraction that allows us to handle the exception at the point where we have all the information we need to handle the exception properly.

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?

Body:
To answer this question properly, let's take a step back and ask an even more fundamental question.

Why is it that we have exceptions in the first place?

We throw exceptions to let the caller of our method know that we couldn't do what we were asked to do.  The type of the exception explains why we couldn't do what we wanted to do.

Let's take a look at some code:

double MethodA()
{
    return PropertyA - PropertyB.NestedProperty;
}

This code can obviously throw a null reference exception if PropertyB is null.  There are two things that we could do in this case to "correct" for this situation.  We could:

Automatically create PropertyB if we don't have it; or

Let the exception bubble up to the calling method.

Creating PropertyB here could be very dangerous.  What reason does this method have to create PropertyB?  Surely this would violate the single responsibility principle.  In all likelihood, if PropertyB does not exist here, it indicates that something has gone wrong.  The method is being called on a partially constructed object or PropertyB was set to null incorrectly.  By creating PropertyB here, we could be hiding a much bigger bug which could bite us later on, such as a bug which causes data corruption.

If, instead, we let the null reference bubble up, we are letting the developer who called this method know, as soon as we can, that something went wrong.  A vital pre-condition of calling this method has been missed.

So in effect, we are throwing early because it separates our concerns much better.  As soon as a fault has occurred, we are letting the upstream developers know about it.

Why we "catch late" is a different story.  We don't really want to catch late, we really want to catch as early as we know how to handle the issue properly.  Some of the time this will be fifteen layers of abstraction later and some of the time this will be at the point of creation.

The point is that we want to catch the exception at the layer of abstraction that allows us to handle the exception at the point where we have all the information we need to handle the exception properly.


问:
Why does a monad use "return" or "unit" rather than "lift"?
This is partly genuine curiosity, and partly a check on my understanding. I'm probably missing the point.

In Haskell, why does a monad use operations called return or unit to describe putting a type into the container -- lifting it into the monadic space? It seems more intuitive to call the operation lift.

Right now, in my (probably incorrect) port of monads into my own project, I'm using (pseudocode):

MyThing.lift(x).bind(f)...

rather than

MyThing.unit(x).bind(f)...

because it's more intuitive for me to think of lifting x into the monadic space.

Is that wrong-headed? I keep getting burned by not thinking abstractly enough, and I suspect that's the case again.

答:
As Benjamin Hodgson mentioned in his comment, the term lift is usually applied to lifting non-monadic functions into the monad.

As for why the function is specifically called return, that is because it is used in the do syntactic sugar, which is meant to resemble an imperative C/ALGOL style code block, which typically used the return keyword to return a value.

Similarly, bind is called SelectMany in .NET, because its monad comprehensions are meant to resemble SQL queries.


答:
The term unit comes from category theory where we define a monad as two natural transformations unit : Identity ~> m and join : m x m ~> m. In case you're curious, bind f = join . fmap f.

return comes from do notation where return looks appropriately algol-ish. It's actually debatable whether this was a good name since it tends to suggest that return is some sort of control flow instead of just being a plain old function.

We usually reserve lift for things that are more like a functor and lift whole functions or monads. lift :: m a -> t m a and liftM :: (a -> b) -> m a -> m b.

Title: Why does a monad use "return" or "unit" rather than "lift"?

Body:
This is partly genuine curiosity, and partly a check on my understanding. I'm probably missing the point.

In Haskell, why does a monad use operations called return or unit to describe putting a type into the container -- lifting it into the monadic space? It seems more intuitive to call the operation lift.

Right now, in my (probably incorrect) port of monads into my own project, I'm using (pseudocode):

MyThing.lift(x).bind(f)...

rather than

MyThing.unit(x).bind(f)...

because it's more intuitive for me to think of lifting x into the monadic space.

Is that wrong-headed? I keep getting burned by not thinking abstractly enough, and I suspect that's the case again.


问:
fast n-gram access data structure
TL;DR

Is there a data structure that'd quickly let me match words at any point (e.g., 'foo' matches 'foobar' and 'zoofoo'), and, ideally, returns a list of "characters that show up after the needle" (e.g., 'foo' should return ['b', $]).

I'm implementing an algorithm that generates random words from a training set of other words.

In simple terms, it's basically like this:

Choose an arbitrary starting point.

Choose the longest suffix of the current word that is contained in at least 2 other words

Choose one of those words at random, and append the next character to the current wor.

GOTO 2 until "next character" is EOW

e.g., if the current word is 'tat', some valid options would be 'potato' and 'tattoo'; if the current word is "ophtalmi", the only option is "ophtalmic", so we search if any words contain "phtalmi", "htalmi", "talmi", and so on.

I've tried a couple of implementations: in one, I've used a trie populated with every suffix of every word. This is very fast at generating words, but populating the trie is VERY slow (~4 million words have not finished in over 10 hours).

In another, I've generated a hash of:

```<code>for word in words:
    for suffix in tails(words):
        for prefix, suffix in prefixes(words): # prefixes("foo") = [("f","oo"),("fo","o"),("foo","")]
            ngrams[prefix].add(suffix) # this is a set
</code>```

and it's much faster at reading the training set, and very fast at generating, but it takes a lot of RAM.

And, finally, the dumb option, of simply searching

```<code>candidates = [word for word in words if string in words]
</code>```

which takes very little memory, but is much slower.

Is there a data structure with the behaviour I need?

答:
I'm thinking some variation of a trie.

A common application of a trie is storing a predictive text or autocomplete dictionary, such as found on a mobile telephone. Such applications take advantage of a trie's ability to quickly search for, insert, and delete entries.

Title: fast n-gram access data structure


答:
The classic answer would be a trie which stores all rotations of words (in scrabble there is a very similar need and a very similar datastructure called a gaddag). It turns out you can do much better (B-tree of words where the lowest level is delta encoded), but the simplest thing you can do is store a sorted list of all rotations of all words in your dictionary and binary search for things. Example:

Our dictionary contains the word w = 'zoofoo', so we store:

```<code>sorted(w[i:] + '^' + w[:i] for i in range(len(w)))
['foo^zoo', 'o^zoofo', 'ofoo^zo', 'oo^zoof', 'oofoo^z', 'zoofoo^']
</code>```

Hey look, one of those entries starts with 'foo'! We can find it via binary search, and reconstruct the original word from 'foo^zoo' by flipping around the ^.

If you can sort your input as well you can do a linear intersection of the input list and the rotation dictionary.

Title: fast n-gram access data structure

Body:
TL;DR

Is there a data structure that'd quickly let me match words at any point (e.g., 'foo' matches 'foobar' and 'zoofoo'), and, ideally, returns a list of "characters that show up after the needle" (e.g., 'foo' should return ['b', $]).

I'm implementing an algorithm that generates random words from a training set of other words.

In simple terms, it's basically like this:

Choose an arbitrary starting point.

Choose the longest suffix of the current word that is contained in at least 2 other words

Choose one of those words at random, and append the next character to the current wor.

GOTO 2 until "next character" is EOW

e.g., if the current word is 'tat', some valid options would be 'potato' and 'tattoo'; if the current word is "ophtalmi", the only option is "ophtalmic", so we search if any words contain "phtalmi", "htalmi", "talmi", and so on.

I've tried a couple of implementations: in one, I've used a trie populated with every suffix of every word. This is very fast at generating words, but populating the trie is VERY slow (~4 million words have not finished in over 10 hours).

In another, I've generated a hash of:

```<code>for word in words:
    for suffix in tails(words):
        for prefix, suffix in prefixes(words): # prefixes("foo") = [("f","oo"),("fo","o"),("foo","")]
            ngrams[prefix].add(suffix) # this is a set
</code>```

and it's much faster at reading the training set, and very fast at generating, but it takes a lot of RAM.

And, finally, the dumb option, of simply searching

```<code>candidates = [word for word in words if string in words]
</code>```

which takes very little memory, but is much slower.

Is there a data structure with the behaviour I need?

Body:
The classic answer would be a trie which stores all rotations of words (in scrabble there is a very similar need and a very similar datastructure called a gaddag). It turns out you can do much better (B-tree of words where the lowest level is delta encoded), but the simplest thing you can do is store a sorted list of all rotations of all words in your dictionary and binary search for things. Example:

Our dictionary contains the word w = 'zoofoo', so we store:

sorted(w[i:] + '^' + w[:i] for i in range(len(w)))
['foo^zoo', 'o^zoofo', 'ofoo^zo', 'oo^zoof', 'oofoo^z', 'zoofoo^']

Hey look, one of those entries starts with 'foo'! We can find it via binary search, and reconstruct the original word from 'foo^zoo' by flipping around the ^.

If you can sort your input as well you can do a linear intersection of the input list and the rotation dictionary.


问:
What's the difference between SocketAddress and ServerSocket in Java?
Learning how to develop a small embedded HTTP server for a class assignment, and the examples given on how to use com.sun.net.httpserver.HttpServer use an InetSocketAddress which extends SocketAddress as the link between client and server. However, all of my previous network programming assignments used Socket and ServerSocket to create raw connections between a server and client to send custom protocols back and forth.

Clearly these two classes are different as they don't share any common ancestor other than java.lang.Object. What is inherently special about each that makes them fundamentally different?

答:
It is all in the name... A typical network socket is a connection between two ports on two machines.

The ServerSocket is the one that waits for clients to connect to it.... it 'binds' to a port, and it 'Listens' for connections, and when they happen, it 'accepts' the connection. The result of the accepted connection is a Java Socket. The client that connected (if it is also Java), also has a Java Socket. You now have two sockets connected to each other.

The Socket is described above.

Now, the address is the details about how to find/identify the remote side of the Socket connection.

A SocketAddress is the abstract class for something that can tell Java where to connect to when contacting a server, and it allows the Sockets to identify remote servers/clients once the connection is made.

An InetSocketAddress is a special SocketAddress designed to represent the standard TCP Protocol address, so it thus has methods to set/query the host name, IP address, and Socket of the remote side of the connection (or, in fact the local side too).

So, the (Inet)Socket address is used to establish Socket connections...

Summary:

ServerSocket is a listener that waits for socket connections to be established.

Socket is the communication channel between two systems (one the server, the other the client).

SocketAddress is an abstract class that identifies an address

InetSocketAddress is a class that is specific for the TCP protocol consisting of IP Addresses/host-names, and port numbers. This is used to establish internet/TCPIP sockets.


答:
You might want to look into Lucene (through Elasticsearch or Solr) or another search-based solution for your problem. Lucene uses an inverted index data structure for efficiently doing lookups on strings. It was at one point exactly a trie, but I'm not entirely sure that the current implementaton can be still considered a trie as its been worked on and optimized so much.

One nice thing about a search engine like Lucene is its built in text analysis features. These analyzers can be chained together to control what strings are placed in the index and also what strings are used to query that index.

Lucene has built in ngram analysis, but you can also easily write your own that takes input text and chops them up in a custom way to satisfy your search requirements.

For a pure Python search solution, you can also check out Whoosh.

Title: fast n-gram access data structure


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

答:
Virtual machine bytecode is simply just another instruction set.  Where we see cases of these instruction sets is generally for portability.  You basically only need one compiler or at least one backend.

The portability comes from choosing a new instruction set which is not too hard to implement on the target real instruction sets.  A stack based instruction set is usually the answer here for portability but not always what is chosen.

As with any instruction set, new or old, you can choose to represent your instructions in any form basically ascii or binary, both can have many various implementations and result in the same machine code being executed.

If you plan for this instruction set to always be VM based and in particular to sit on top of an operating system, you can certainly if you choose, to implement higher level functions like print or file i/o into the instruction set.  Something you would not necessarily do when targeting a real machine code instruction set implemented in hardware, since the hardware itself rarely has such complicated functions in the instruction set.  system calls to other piles of code yes, but not direct implementation.  The virtual instruction set as far as that instruction set does has whatever you define as the level of functionality of an individual instruction/operation.  if you dont have these high level print, file i/o, etc functions in the virtual instruction set then, you will have to implement some other solution like a virtual address space with virtual devices that have to be implemented as the virtual instruction set wont want to know about real hardware details, that defeats the portability and the advantage of one compiler for all platforms.


问:
Scrum: how to integrate work done by an overachieving developer out of band?
We have a "typical" SCRUM team and we commit to work for a sprint, and also maintain a backlog. Recently we have run into a problem of trying to integrate/handle the work of an overachieving developer doing out of band work (choosing to work outside of the normal working hours/sprint).

To give an example, if the team takes in 50 points of work, let's say that they will complete all that work within the SCRUM framework by the end of the sprint and they and the company is happy. One of the team members decides to work on their own, on a backlog item, on their own free time. They do not check in this work, but instead save it (we use TFS and it is in a shelveset).

How to handle this? A few of the problems ..

During the next sprint this team members says the programming work is 99% done and just needs code review and testing. How do you deal with this in the SCRUM and agile methodology?

Other developers complain about not being involved in design decisions related to these stories, since the work was done out of band.

Our product owner is tempted to pull in this "free" work and the overachieving members is likely doing this on purpose in order to get more features into the product that the team otherwise would not be able to accomplish in the sprint(s). There is a view that this is breaking the "process". Obviously QA, UI and documentation work still need to be done on this work.

I see a lot of discussion about not forcing a SCRUM team to work overtime, but what about a member of the team working above and beyond the expectations put forth during planning and execution of sprints? I would hesitate to reign this person in and say you cannot work extra (cautioning on burn out of course), but at the same time it seems to be causing some issues with certain members of the team (but not all).

How to integrate work done by an overachieving member into the SCRUM and agile process for software development?

答:
we faced with same thing as well, basically we committed something like 20 points but at last week or even middle of sprint we ran out of coding task however because of Testing and rest of process we didn't risk to pick another PBI, So what programmers did was to  to look into the backlog and start developing future PBIs (silently!) and informing the rest of team in planning that PBI is ready for code review and testing! just like you said.

It actually raised some concern from our POs that it seems we are capable more but we don't fully utilize our team's potential, which was partly true but yes, maybe our programmers could do more but our testers couldn't follow up that speed so there was a risk to fail the sprint. after thinking about this issue we found out that we need to change our view about scrum and the main issue is that people don't want to take that risk is because we Commit PBIs so team didn't feel good to take that risk of picking new PBIs in case that we have free programmer.

Simply we started to Forecast PBIs rather than make commitment. Forecasting basically means we  pick 25 points at planning and start of sprint, And when programmer gets free at middle of sprint, because there is no more coding task so he/she picks one of the future PBI and put it in Current Sprint and start working on it, if the PBI could pass all of the process(testing, merging and etc) within same sprint, it is bonus point for team if NOT we don't fail the sprint because of that PBI and just carrying forward the remaining work(testing or meging or etc) to the next sprint and re poker for remaining job. So it can be done in two different sprint in worse case scenario. I know it might sounds like Scrumbut but it actually improved the way that we work. I just can summarize its benefits as below:

It defeats the phobia of failing sprint because of taking the risk of taking more PBI

It makes the extra work of your programmers and team visible

It increases your team velocity

However maybe for a team with less experience, maybe it reduce the push that commitment gives to the team to finish the PBIs


问:
Did the gradual shift in methodology of writing code affect system performance? And Should I care?
TD;DR:

There was some confusion as to what I was asking, so here is the driving idea behind the question:

I always intended the question to be what it is. I may not have articulated it well originally. But intent have always been "is modular, separated, loose coupled, decoupled, refactored code" markedly slower by its own nature than "monolithic single-unit, do-everything in one place, one file, tightly coupled" code. The rest is just details and various manifestations of this that I came across then or now or will later. It is slower for sure on some scale. Like a non-defragged disk, you have to pick up the pieces from everywhere. It's slower. For sure. But should I care?

And the question is not about...

not about micro-optimization, premature optimization, etc.  It is not about "optimize this or that part to death".

What is it then?

It is about the overall methodology and techniques and ways of thinking about writing code that emerged over time:

"inject this code into your class as a dependency"

"write one file per class"

"separate your view from your database, controller, domain".

don't write spaghetti homogenious single codeblock, but write many separate modular components that work together

It is about the way and the style of code that is currently - within this decade - seen and advocated in most frameworks, advocated at conventions, passed on via the community.  It is a shift in thinking from 'monolithic blocks' to 'microservices'.  And with that comes the price in terms of machine-level performance and overhead, and some programmer-level overhead as well.

Original Question follows:

In Computer Science field, I have noticed a notable shift in thinking when it comes to programming.  I come across the advice quite often that goes like this:

write smaller function-wise code (more testable and maintainable this way)

refactor existing code into smaller and smaller chunks of code until most of your methods/functions are just a few lines long and it is clear what is their purpose (which creates more functions, compared to a larger monolithic block)

write functions that only do one thing - separation of concerns, etc (which usually creates more functions and more frames on a stack)

create more files (one class per file, more classes for decomposition purposes, for layer purposes such as MVC, domain architecture, design patterns, OO, etc, which creates more file system calls)

This is a change compared to the "old" or "outdated" or "spaghetti" coding practices where you have methods spanning 2500 lines, and big classes and god objects doing everything.

My question is this:

when it call comes down to machine code, to 1s and 0s, to assembly instructions, to HDD platters, should I be at all concerned that my perfectly class-separated OO code with variety of refactored small-to-tiny functions and methods generates too much extra overhead?

Details

While I am not intimately familiar with how OO code and its method calls are handled in ASM in the end, and how DB calls and compiler calls translate to moving actuator arm on a HDD platter, I do have some idea.  I assume that each extra function call, object call, or "#include" call (in some languages), generate an extra set of instructions, thereby increasing code's volume and adding various "code wiring" overheads, without adding actual "useful" code.  I also imagine that good optimizations can be done to ASM before it is actually ran on the hardware, but that optimization can only do so much too.

Hence, my question -- how much overhead (in space and speed) does well-separated code (code that is split up across hundreds of files, classes, and design patterns, etc) actually introduce compared to having "one big method that contains everything in one monolithic file", due to this overhead?

UPDATE for clarity:

I am assuming that taking the same code and splitting it, refactoring it out, decoupling it into more and more functions and objects and methods and classes will result in more and more parameter passing between smaller code pieces.  Because for sure, refactoring code has to keep the thread going, and that requires parameter passing.  More methods or more classes or more Factory Methods design patterns, results in more overhead of passing various bits of information more than it is the case in a single monolithic class or method.

It was said somewhere (quote TBD) that up to 70% of all code is made up of ASM's MOV instruction - loading CPU registers with proper variables, not the actual computation being done.  In my case, you load up CPU's time with PUSH/POP instructions to provide linkage and parameter passing between various pieces of code.  The smaller you make your pieces of code, the more overhead "linkage" is required.  I am concerned that this linkage adds to software bloat and slow-down and I am wondering if I should be concerned about this, and how much, if any at all, because current and future generations of programmers who are building software for the next century, will have to live with and consume software built using these practices.

UPDATE:  Multiple files

I am writing new code now that is slowly replacing old code.  In particular I've noted that one of the old classes was a ~3000 line file (as mentioned earlier).  Now it is becoming a set of 15-20 files located across various directories, including test files and not including PHP framework I am using to bind some things together. More files are coming as well. When it comes to disk I/O, loading multiple files is slower than loading one large file.  Of course not all files are loaded, they are loaded as needed, and disk caching and memory caching options exist, and yet still I believe that loading multiple files takes more processing than loading a single file into memory.  I am adding that to my concern.

UPDATE: Dependency Inject everything

Coming back to this after a while.. I think my question was misunderstood.  Or maybe I chose to misunderstand some answers.  I am not talking about micro-optimizing as some answers have singled out, (at least I think calling what I am talking about micro-optimization is a misnomer) but about the movement of "Refactor code to loosen tight coupling", as a whole, at every level of the code.  I came from Zend Con just recently where this style of code has been one of the core points and centerpieces of the convention.  Decouple logic from view, view from model, model from database, and if you can, decouple data from the database.  Dependency-Inject everything, which sometimes means just adding wiring code (functions, classes, boilerplate) that does nothing, but serves as a seam/hook point, easily doubling code size in most cases.

UPDATE 2:  Does "separating code into more files" significantly affect performance (at all levels of computing)

How does philosophy of compartmentalize your code into multiple files impact today's computing (performance, disk utilization, memory management, CPU processing tasks)?

I am talking about

Before...

In a hypothetical yet quite real not so distant past, you could easily write one mono-block of a file that does has model and view and controller spaghetti or not-spaghetti-coded, but that runs everything once it is already loaded.  Doing some benchmarks in the past using C code I found out that it is MUCH faster to load a single 900Mb file into memory and process it in large chunks than it is to load a bunch of smaller files and process them in a smaller peace-meal chunks doing the same work in the end.

.. And Now*

Today I find myself looking at code that shows a ledger, that has features like .. if an item is an "order", show order HTML block.  If a line item can be copied, print HTML block that displays an icon and HTML parameters behind it allowing you to make the copy.  If the item can be moved up or down, display the appropriate HTML arrows.  Etc.  I can, through Zend Framework create partial() calls, which essentially means "call a function that takes your parameters and inserts them into a separate HTML file that it also calls".  Depending on how detailed I want to get, I can create separate HTML functions for the tiniest parts of the ledger.  One for arrow up, arrow down, one for "can I copy this item", etc.  Easily creating several files just to display a small part of the webpage.  Taking my code and behind-the-scenes Zend Framework code, the system/stack probably calls close to 20-30 different files.

What?

I am interested in aspects, the wear and tear on the machine that is created by compartmentalizing code into many smaller separate files.

For example, loading more files means having them located in various places of the file system, and in various places of physical HDD, which means more HDD seek and read time.

For CPU it probably means more context switching and loading various registers.

In this sub-block (update #2) I am interested more strictly in how using multiple files to do the same tasks that could be done in a single file, affect system performance.

Using Zend Form API vs simple HTML

I used Zend Form API with latest and greatest modern OO practices, to build an HTML form with validation, transforming POST into domain objects.

It took me 35 files to make it.

```<code>35 files =
    = 10 fieldsets x {programmatic fieldset + fieldset manager + view template}
    + a few supporting files
</code>```

All of which could be replaced with a a few simple HTML + PHP + JS + CSS files, perhaps total of 4 light-weight files.

Is it better? Is it worth? ... Imagine loading 35 files + numerous Zend Zramework library files that make them work, vs 4 simple files.

答:
Well 20+ years ago, which I am guessing you are not calling new and not "old or bad", the rule was to keep functions small enough to fit on a printed page.  We had dot matrix printers then so the number of lines was somewhat fixed generally only one or two choices for number of lines per page...definitely less than 2500 lines.

You are asking many sides of the problem, maintainability, performance, testability, readability.  The more you lean toward performance the less maintainable and readable the code will become, so you have to find your comfort level which can and will vary for each individual programmer.

As far as code produced by the compiler (machine code if you will), the larger the function the more opportunity for needing to spill intermediate values in registers to the stack.  When stack frames are used the stack consumption is in larger chunks.  The smaller the functions the more opportunity for the data staying more in registers and the less dependence on the stack.  Smaller chunks of stack needed per function naturally.  Stack frames have pros and cons for performance.  More smaller functions means more function setup and cleanup.  Of course it also depends on how you compile, what opportunities you give the compiler.  You may have 250 10 line functions instead of one 2500 line function, the one 2500 line function the compiler is going to get if it can/chooses to optimize across the whole thing. But if you take those 250 10 line functions and spread them across 2, 3, 4, 250 separate files, compile each file separately then the compiler wont be able to optimize out nearly as much dead code as it could have.  the bottom line here is there are pros and cons to both and it is not possible to put a general rule on this or that is the best way.

Reasonable sized functions, something a person can see on a screen or page (in a reasonable font), is something they can consume better and understand than code that is quite large.  But if it is just a small function with calls to many other small functions that call many other small functions you need several windows or browsers up to understand that code so you didnt buy anything on the readability side.

the unix way is to make using my term, nicely polished lego blocks.  Why would you use a tape function this many years after we stopped using tapes?  Because the blob did its job very well and on the back side we can replace the tape interface with a file interface and take advantage of the meat of the program.  Why re-write cdrom burning software just because scsi went away as the dominant interface replaced by ide (then to come back later).  Again take advanatage of the polished sub blocks and replace one end with a new interface block (also understand the hardware designers simply tacked an interface block on the hardware designs to in some cases making a scsi drive have an ide to scsi interface.  To shorten this, build reasonable sized polished lego blocks each with a well defined purpose and well defined inputs and outputs.  you can wrap tests around those lego blocks and then take the same block and wrap user interface and operating system interfaces around the same block and the block, in theory being well tested and well understood wont need to be debugged, just the additional new blocks added on each end.  so long as all of your blocks interfaces are well designed and the functionality well understood you can build a great many things with minimal if any glue.  just like with blue and red and black and yellow lego blocks of known sizes and shapes you can make a great many things.

Every individual is different, their definition of polished and well defined and tested and readable vary.  It is not unreasonable for example for a professor to dictate programming rules not because they may or may not be bad for you as a professional, but in some cases to make the job of reading and grading your code easier on the professor or grad student assistants...You are equally likely, professionally, to find that each job may have different rules for various reasons, usually one or a few people in power have their opinion on something, right or wrong and with that power they can dictate that you do it there way (or quit, get fired, or somehow come to power).  These rules are as often opinion based as they are based in some kind of fact about readability, performance, testability, portability.


问:
About AST construction in LL1 non recursive parser
I have implemented a LL1 parser in a non recursive approach with a explicit stack.

The following algorithm is from the Dragon Book:

```<code>set zp to point to the first symbol of w;
set X to the top stack symbol;
while ( X != $ ) { /* stack is not empty */
    if ( X is a )
       pop the stack and advance zp;
    else if ( X is a terminal )
       error();
    else if ( M[X, a] is an error entry )
       error();
    else if ( M[X,a] = X -+ Y1Y2 Yk ) {
       output the production X -+ YlY2 - . Yk;
       pop the stack;
       push Yk, Yk-1,. . . , Yl onto the stack, with Yl on top;

    set X to the top stack symbol;
}
</code>```

The book says:

The parser is controlled by a program that considers X, the symbol on
  top of the stack, and a, the current input symbol. If X is a
  nonterminal, the parser chooses an X-production by consulting entry
  M[X, a] of the parsing table IM. (Additional code could be executed
  here, for example, code to construct a node in a parse tree.)
  Otherwise, it checks for a match between the terminal X and current
  input symbol a.

However i need more info on how to construct the expression tree nodes under this approach. I have a node hierarchy of UnaryOperator, BinaryOperator, etc but dont know where to instanciate it.

Yet i havent found any simple example of this (with for example the arithmetic language).

答:
It happens just as the cited text from the book explains: when you expand a nonterminal via its grammar rule (given by M[X, a]), then you can create a corresponding node.

Say you have rules of the following form:

```<code>Term -> Factor Term'
Term' -> * Term | / Term | ε

Factor -> x | y | ... (simplified for individual numbers, letters, what-have-you)
</code>```

Then, once you expand Term -> Factor Term' you can create a Term node with two child nodes. When you successfully parse the first number via the Factor -> ... rule (this is the first if in your example code now) you can attribute this number to the already created Factor node.

Next, you expand for example Term' -> * Term via M[Term',*] and create a new Term node.

Continuing, you will parse the * and annotate it at your Term' node, expand Term -> Factor Term' once more, thus creating two more nodes, successfully parse a Factor and annotate its number to the second Factor node and finally, on end of input you will parse Term' via the epsilon production (M[Term',$] = ε), which tells you that you can remove that Term' node (though that may be optional).

What you end up with for an input string like 3*4 is then a tree like this:

Term ( Factor(3), Term' (*, Term ( Factor(4) ) ) )

In a post-processing step, you could simplify the resulting tree, as nonterminals like Term' stem from making the grammar non-left-recursive, but are otherwise unsuitable for the resulting AST, so you would want to reverse the grammar transformation on your resulting tree to get something like this:

Mult (Number(3), Number(4))

Body:
It happens just as the cited text from the book explains: when you expand a nonterminal via its grammar rule (given by M[X, a]), then you can create a corresponding node.

Say you have rules of the following form:

Term -> Factor Term'
Term' -> * Term | / Term | ε

Factor -> x | y | ... (simplified for individual numbers, letters, what-have-you)

Then, once you expand Term -> Factor Term' you can create a Term node with two child nodes. When you successfully parse the first number via the Factor -> ... rule (this is the first if in your example code now) you can attribute this number to the already created Factor node.

Next, you expand for example Term' -> * Term via M[Term',*] and create a new Term node.

Continuing, you will parse the * and annotate it at your Term' node, expand Term -> Factor Term' once more, thus creating two more nodes, successfully parse a Factor and annotate its number to the second Factor node and finally, on end of input you will parse Term' via the epsilon production (M[Term',$] = ε), which tells you that you can remove that Term' node (though that may be optional).

What you end up with for an input string like 3*4 is then a tree like this:

Term ( Factor(3), Term' (*, Term ( Factor(4) ) ) )

In a post-processing step, you could simplify the resulting tree, as nonterminals like Term' stem from making the grammar non-left-recursive, but are otherwise unsuitable for the resulting AST, so you would want to reverse the grammar transformation on your resulting tree to get something like this:

Mult (Number(3), Number(4))


答:
Depends how smart your compiler is. Generally, trying to outsmart the optimizer is a bad idea and may actually rob the compiler of opportunities to optimize. For starters, you probably don't have any clue whatsoever what it can do and most of what you do actually influences how well it does that too.

Premature optimization is the notion of programmers trying to do that and ending up with hard to maintain code that wasn't actually on the critical path of what they were trying to do. Trying to squeeze out as much CPU as possible when most of the time your app is actually blocked waiting for IO events, is something I see a lot for example.

The best is to code for correctness and use a profiler to find actual performance bottlenecks, and fix those by analyzing what is on the critical path and whether it can be improved. Often a few simple fixes go a long way.

Title: Did the gradual shift in methodology of writing code affect system performance? And Should I care?

Body:
TD;DR:

There was some confusion as to what I was asking, so here is the driving idea behind the question:

I always intended the question to be what it is. I may not have articulated it well originally. But intent have always been "is modular, separated, loose coupled, decoupled, refactored code" markedly slower by its own nature than "monolithic single-unit, do-everything in one place, one file, tightly coupled" code. The rest is just details and various manifestations of this that I came across then or now or will later. It is slower for sure on some scale. Like a non-defragged disk, you have to pick up the pieces from everywhere. It's slower. For sure. But should I care?

And the question is not about...

not about micro-optimization, premature optimization, etc.  It is not about "optimize this or that part to death".

What is it then?

It is about the overall methodology and techniques and ways of thinking about writing code that emerged over time:

"inject this code into your class as a dependency"

"write one file per class"

"separate your view from your database, controller, domain".

don't write spaghetti homogenious single codeblock, but write many separate modular components that work together

It is about the way and the style of code that is currently - within this decade - seen and advocated in most frameworks, advocated at conventions, passed on via the community.  It is a shift in thinking from 'monolithic blocks' to 'microservices'.  And with that comes the price in terms of machine-level performance and overhead, and some programmer-level overhead as well.

Original Question follows:

In Computer Science field, I have noticed a notable shift in thinking when it comes to programming.  I come across the advice quite often that goes like this:

write smaller function-wise code (more testable and maintainable this way)

refactor existing code into smaller and smaller chunks of code until most of your methods/functions are just a few lines long and it is clear what is their purpose (which creates more functions, compared to a larger monolithic block)

write functions that only do one thing - separation of concerns, etc (which usually creates more functions and more frames on a stack)

create more files (one class per file, more classes for decomposition purposes, for layer purposes such as MVC, domain architecture, design patterns, OO, etc, which creates more file system calls)

This is a change compared to the "old" or "outdated" or "spaghetti" coding practices where you have methods spanning 2500 lines, and big classes and god objects doing everything.

My question is this:

when it call comes down to machine code, to 1s and 0s, to assembly instructions, to HDD platters, should I be at all concerned that my perfectly class-separated OO code with variety of refactored small-to-tiny functions and methods generates too much extra overhead?

Details

While I am not intimately familiar with how OO code and its method calls are handled in ASM in the end, and how DB calls and compiler calls translate to moving actuator arm on a HDD platter, I do have some idea.  I assume that each extra function call, object call, or "#include" call (in some languages), generate an extra set of instructions, thereby increasing code's volume and adding various "code wiring" overheads, without adding actual "useful" code.  I also imagine that good optimizations can be done to ASM before it is actually ran on the hardware, but that optimization can only do so much too.

Hence, my question -- how much overhead (in space and speed) does well-separated code (code that is split up across hundreds of files, classes, and design patterns, etc) actually introduce compared to having "one big method that contains everything in one monolithic file", due to this overhead?

UPDATE for clarity:

I am assuming that taking the same code and splitting it, refactoring it out, decoupling it into more and more functions and objects and methods and classes will result in more and more parameter passing between smaller code pieces.  Because for sure, refactoring code has to keep the thread going, and that requires parameter passing.  More methods or more classes or more Factory Methods design patterns, results in more overhead of passing various bits of information more than it is the case in a single monolithic class or method.

It was said somewhere (quote TBD) that up to 70% of all code is made up of ASM's MOV instruction - loading CPU registers with proper variables, not the actual computation being done.  In my case, you load up CPU's time with PUSH/POP instructions to provide linkage and parameter passing between various pieces of code.  The smaller you make your pieces of code, the more overhead "linkage" is required.  I am concerned that this linkage adds to software bloat and slow-down and I am wondering if I should be concerned about this, and how much, if any at all, because current and future generations of programmers who are building software for the next century, will have to live with and consume software built using these practices.

UPDATE:  Multiple files

I am writing new code now that is slowly replacing old code.  In particular I've noted that one of the old classes was a ~3000 line file (as mentioned earlier).  Now it is becoming a set of 15-20 files located across various directories, including test files and not including PHP framework I am using to bind some things together. More files are coming as well. When it comes to disk I/O, loading multiple files is slower than loading one large file.  Of course not all files are loaded, they are loaded as needed, and disk caching and memory caching options exist, and yet still I believe that loading multiple files takes more processing than loading a single file into memory.  I am adding that to my concern.

UPDATE: Dependency Inject everything

Coming back to this after a while.. I think my question was misunderstood.  Or maybe I chose to misunderstand some answers.  I am not talking about micro-optimizing as some answers have singled out, (at least I think calling what I am talking about micro-optimization is a misnomer) but about the movement of "Refactor code to loosen tight coupling", as a whole, at every level of the code.  I came from Zend Con just recently where this style of code has been one of the core points and centerpieces of the convention.  Decouple logic from view, view from model, model from database, and if you can, decouple data from the database.  Dependency-Inject everything, which sometimes means just adding wiring code (functions, classes, boilerplate) that does nothing, but serves as a seam/hook point, easily doubling code size in most cases.

UPDATE 2:  Does "separating code into more files" significantly affect performance (at all levels of computing)

How does philosophy of compartmentalize your code into multiple files impact today's computing (performance, disk utilization, memory management, CPU processing tasks)?

I am talking about

Before...

In a hypothetical yet quite real not so distant past, you could easily write one mono-block of a file that does has model and view and controller spaghetti or not-spaghetti-coded, but that runs everything once it is already loaded.  Doing some benchmarks in the past using C code I found out that it is MUCH faster to load a single 900Mb file into memory and process it in large chunks than it is to load a bunch of smaller files and process them in a smaller peace-meal chunks doing the same work in the end.

.. And Now*

Today I find myself looking at code that shows a ledger, that has features like .. if an item is an "order", show order HTML block.  If a line item can be copied, print HTML block that displays an icon and HTML parameters behind it allowing you to make the copy.  If the item can be moved up or down, display the appropriate HTML arrows.  Etc.  I can, through Zend Framework create partial() calls, which essentially means "call a function that takes your parameters and inserts them into a separate HTML file that it also calls".  Depending on how detailed I want to get, I can create separate HTML functions for the tiniest parts of the ledger.  One for arrow up, arrow down, one for "can I copy this item", etc.  Easily creating several files just to display a small part of the webpage.  Taking my code and behind-the-scenes Zend Framework code, the system/stack probably calls close to 20-30 different files.

What?

I am interested in aspects, the wear and tear on the machine that is created by compartmentalizing code into many smaller separate files.

For example, loading more files means having them located in various places of the file system, and in various places of physical HDD, which means more HDD seek and read time.

For CPU it probably means more context switching and loading various registers.

In this sub-block (update #2) I am interested more strictly in how using multiple files to do the same tasks that could be done in a single file, affect system performance.

Using Zend Form API vs simple HTML

I used Zend Form API with latest and greatest modern OO practices, to build an HTML form with validation, transforming POST into domain objects.

It took me 35 files to make it.

```<code>35 files =
    = 10 fieldsets x {programmatic fieldset + fieldset manager + view template}
    + a few supporting files
</code>```

All of which could be replaced with a a few simple HTML + PHP + JS + CSS files, perhaps total of 4 light-weight files.

Is it better? Is it worth? ... Imagine loading 35 files + numerous Zend Zramework library files that make them work, vs 4 simple files.


问:
Calculating last Sprint's Focus Factor
We have finished our Sprint in half the expected time and now we want to compute our focus factor to use in the next Sprint. Though, by doing the math by the book, we get an awful number. How are we calculating it wrong? Please take a look bellow:

Team composition: 3

Sprint length: 2    weeks

Team availability: 28 days
(discounting team members shared with
other teams)

Estimated focus factor: 70%

Estimated velocity: 19 ideal days
(derived from:  28 days * 0.7 focus
factor)

Actual velocity: 9.8 days (we
finished the whole Sprint in half the
expected time, clearly overestimated)

which gives us a focus factor of...

Actual focus factor (to be used in
the next Sprint): 35% (9.8 actual
velocity / 28 available man-days)

Acording to Scrum And Xp From The Trenches we calculate Focus Factor as "(actual velocity) / (available man-days)". Though, by finishing the Sprint in half time and doing the math, we get a focus factor of 35%! What are we doing wrong?

答:
I have a different opinion on this. We have 3 parameters to consider here. Those are;

Allocated Time in man hours (AT): Time spent by a person while allocated to a task, say task1 (e.g. if a person work for 9 hours daily and normally spend 1 hour for lunch, coffee etc. then per day time allocated for work is 8 hours, so AT = 8)

Focused Time in man hours (FT): The amount of time a person has actually managed to focus on the above task1 (this is going to be most of the time <= AT)

Burn Down in man hours (BD): By focusing on task1 person will complete a certain amount of estimated work. That is termed as ‘burn down’.

Now let’s take an example

AT = 16 hours (i.e. 8 hours / day for 2 days)

FT = 12 hours (on average he is distracted by 2 hours per day, say in meetings etc.)

BD = 10 man hours (This is the estimate of the task1)

Focus factor = FT/AT = (6 * 2)/(8 * 2) = 0.75

But this does not take into account the amount of work completed from the estimated tasks (burn down). This person has spent 12 hours (with good focus) to complete a task estimated for 10 man hours. So in order to get that effect into focus factor it is better and reasonable to focus time by burn down in above formula.

Focus factor = BD/AT = (10)/(8 * 2) = 0.625

So in my opinion the focus factor formula should be:

Focus factor = Burn down / Allocated Time

Title: Calculating last Sprint's Focus Factor


答:
First of all, exceptions are for exceptional situations. In your example, no figure can be calculated if the raw data is not present because it could not be loaded.

From my experience, it's good practice to abstract exceptions while walking up the stack. Typically the points where you want to do this is whenever an exception crosses the boundary between two layers.

If there's an error with gathering your raw data in the data layer, throw an exception to notify whoever requested the data. Do not attempt to work around this issue down here. The complexity of the handling code can be very high. Also the data layer is only responsible for requesting data, not for handling errors that occure while doing this. This is what meant by "throw early".

In your example the catching layer is the service layer. The service itself is a new layer, sitting over the data access layer. So you want to catch the exception there. Perhaps your service has some failover infrastructure and tries to request the data from another repository. If this also fails, wrap the exception inside something the caller of the service understands (if it's an web service this might be an SOAP fault). Set the original exception as inner exception so that the later layers can log exactly what went wrong.

The service fault may be catched by the layer calling the service (for example the UI). And this is what meant by "catch late". If you are not able to handle the exception in an lower layer, rethrow it. If the top most layer can't handle the exception, handle it! This might include logging or presenting it.

The reason why you should rethrow exceptions (like described above by wrapping them in more general exeptions) is, that the user is very likely not able to understand that there was an error because, for example, a pointer pointed to invalid memory. And he doesn't care. He only care's that the figure could not be calculated by the service and this is the information that should be displayed to him.

Going futher you can (in an ideal world) completely leave out try/catch code from the UI. Instead use an global exception handler that is able to understand the exceptions that are possibly thrown by the lower layers, writes them into some log and wraps them into error objects that contain meaningful (and possibly localized) information of the error. Those objects can easily be presented to the user in any form you wish (message boxes, notifications, message toasts, and so on).


问:
Is CodeFirst intended for large scale applications?
I've been reading up on Entity Framework, in particular, EF 4.1 and following this link ( http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx) and it's guide on Code First.

I find it neat but I was wondering, is Code First supposed to be just a solution for rapid development where you can just jump right in without much planning or is it actually intended to be used for large scale applications?

答:
Code First is not suitable for large scale applications. Large scale apps development turnaround is very huge.

Typically life cycle of your business app is like,

Version 1 is in production

Version 2 is in beta

Version 3 is in active development

Version 4 is in planning.

And there are other Cross Application communication bridges, some scheduled tasks, some third party integration, web services for some different communicating devices such as mobile etc.

Eventually Code First uses Entity Model's ObjectContext, Older EF generating EDMX and using ObjectContext with EntityObject was really sufficient for everything. You could easily customize text template to generate code. Detect Changes method is slower with ObjectContext implementation, but instead of generating proxy, EF team could have easily improved Detect Changes speed instead of reinventing code first.

Automated Migration

Automated Migration sounds good in theory, but impossible in practice once you go live. It is only good for prototyping, developing some quick demos.

Code First Migration is not at all suitable in such system. Version 1 and Version 2 most likely talk to same database. Version 3 and Version 4 is usually staging and has different database.

Database First

Database First is practical approach, it is easy to compare and visualize and maintain SQL Scripts. DBAs can work with easily.

Text Templates

We created our own Text Templates to query and create EDMX and ObjectContext with little custom implementation that addresses performance issues. There are multiple applications with multiple versions communicating to same database without any problems.

To me, right clicking on .tt file and clicking "Run Custom Tool" is by far fastest and easiest step then writing classes, configuring and creating model.


问:
When changing a class/method and you already have passing unit tests, should you change then test or write a test then change?
Say I have a class with a single constructor that accepts 2 parameters and initialises itself using those parameters. I have written tests for this and they are all passing.

I later realise I need to make an addition to the constructor to accept three parameters. Should I

a) Add in the new parameter, watch my tests break and try and fix it

b) Rewrite existing tests to test for the new expected behavior, watch them initially fail and then add to the class (this to me seems a more TDD way)

From a TDD point of view, I think that option 'b' makes more sense. However, option 'a' (to me) seems like a more natural approach.

Is there any standard way that most people do this?

答:
I guess what is more natural depends on whether you are a test driven developer or a test last developer.

Quoting "Growing Object-Oriented Software, Guided by Tests" (Steve Freeman, Nat Pryce), the golden rule of TDD is:
Never write new functionality without a failing test.


问:
Sharing classes or interfaces between different projects
I was looking for some answers in SO or here, but without any results, that's why I would ask you.

Let's assume I have a two different projects - for example server part and client part of an app. I'm developing my own part, while my friend is making the second one. But both of us should use some common interfaces like User or AccountInfo or ChangableAccount... whatever in order to ensure a compatibility. For example if a clients send a User data to server, then the server should operate on the same class. The same with interfaces etc. Moreover, if there are any changes in a common interface, both projects should adjust its code to the new situation.

The only solution I can see now is, to create a one extra project in which all common things are defined. We, me and my friend, should add this project as a dependency to a main project (client or server). Shared project can be managed by some version control system, so we have always the most up-to-date state.

What other solution would you suggest? How such problems are solved in professional apps?

答:
Your solution is the right one. Put the shared code into a another project that builds its own JAR file, and use it in both projects. When building the JAR file, you may want to include the version in the name, e.g. in Debian style;

```<code>libmyproject-shared-1.0.jar
</code>```

It doesn't prevent versioning trouble, but it should help. I've never used Maven, but I understand it can help in this situation.

Body:
Your solution is the right one. Put the shared code into a another project that builds its own JAR file, and use it in both projects. When building the JAR file, you may want to include the version in the name, e.g. in Debian style;

libmyproject-shared-1.0.jar

It doesn't prevent versioning trouble, but it should help. I've never used Maven, but I understand it can help in this situation.