问:
Why is entangling injectable with class that uses it a bad practice?
I have had this argument for a while, because I have noticed some people prefer "readable" code over properly structured one. So in the example I am showing, basically I have this Mapper class in which different Mappable instances are injected and the Mapper uses the instances to know how to map some data. The question here is, why is it a bad practice to do so. I suspect that the problems are: the method is static, the factory is in the wrong class, making the Mapper hard coupled to the Map classes.

```<code>interface Mappable {
    public function getMetaData();
    public function setMetaData(array $metaData);
}

class BaseMap implements Mappable {
    protected $metaData = [];

    public function getMetaData() {
        return $this->metaData;
    }

    public function setMetaData(array $metaData) {
        $this->metaData = $metaData;
    }

    /**
     * Possible Code Smell
     */
    public static function getNewMapper() {
        return new Mapper(new static);
    }
}

class MapA extends BaseMap {
    protected $metaData = [
        'backField1' => 'frontField1',
        'backField2' => 'frontField2'
    ];
}

class MapB extends BaseMap {
    protected $metaData = [
        'backFieldA' => 'frontFieldA',
        'backFieldB' => 'frontFieldB'
    ];
}

class Mapper {
    private $map;

    public function __construct(Mappable $map) {
        $this->setMap($map);
    }

    public function setMap(Mappable $map) {
        $this->map = $map;
    }

    public function parseData($dataRow) {
        $metaData = $this->map->getMetaData();
        $parsedDataRow = [];

        foreach($dataRow as $columnName => $columnValue) {
            if(isset($metaData[$columnName]))
                $parsedDataRow[$metaData[$columnName]] = $columnValue;
        }

        return $parsedDataRow;
    }
}

// Probably correct
$mapper = new Mapper(new MapA());
print_r($mapper->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']));

$mapper->setMap(new MapB());
print_r($mapper->parseData(['backFieldA' => 'fooA', 'backFieldB' => 'barB']));

// Possible Code Smell
print_r(MapA::getNewMapper()->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']));
print_r(MapB::getNewMapper()->parseData(['backFieldA' => 'fooA', 'backFieldB' => 'barB']));
</code>```

UML class diagram:

答:
I am not a PHP expert, but I can read the code.

When I see this code

```<code>// Probably correct
$mapper = new Mapper(new MapA());
print_r($mapper->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']));
</code>```

Then I think to myself, why do I need to instantiate a Mapper with MapA.
I would want to have 1 class that both holds the data and knows how to map.
I would want class Mapper to extend BaseMap and MapA to extend Mapper

Then, I can simply

```<code>$mapper = new MapA();
print_r($mapper->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']));
</code>```

Granted, MapA might not be the best name, you could have used the name of the real mapping method.

Edit:

The counter argument for that is that this leaves the current design flexible, one could use different Mapper classes. My counter counter argument; that feature is not intuitive because the only factory method you have only returns Mapper.

That means that your approach is not caller friendly and not intuitive. If you want to keep the design flexible, then you should remove the static factory method. You could replace it with a comment that points out that this can be used by different mappers.

Finally, you should design with YAGNI in mind, refactoring for new requirements is okay.

OwnerDisplayName: ziGi

Body:
I am not a PHP expert, but I can read the code.

When I see this code

// Probably correct
$mapper = new Mapper(new MapA());
print_r($mapper->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']));

Then I think to myself, why do I need to instantiate a Mapper with MapA.
I would want to have 1 class that both holds the data and knows how to map.
I would want class Mapper to extend BaseMap and MapA to extend Mapper

Then, I can simply

$mapper = new MapA();
print_r($mapper->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']));

Granted, MapA might not be the best name, you could have used the name of the real mapping method.

Edit:

The counter argument for that is that this leaves the current design flexible, one could use different Mapper classes. My counter counter argument; that feature is not intuitive because the only factory method you have only returns Mapper.

That means that your approach is not caller friendly and not intuitive. If you want to keep the design flexible, then you should remove the static factory method. You could replace it with a comment that points out that this can be used by different mappers.

Finally, you should design with YAGNI in mind, refactoring for new requirements is okay.

OwnerDisplayName: tomdemuyt


答:
The other problem i see with your code is your inheritance is making contracts with classes it should not need to and is really breaking all oop practices.  This approach allows for less code and cleaner code but also follows the convention of grouped functionality and multiple inheritance.   </p>

```<code>interface Mappable {
    public function getMetaData();
    public function setMetaData(array $metaData);
}

abstract class BaseMap implements Mappable {
    protected $metaData = [];

    public function getMetaData() {
        return $this->metaData;
    }

    public function setMetaData(array $metaData) {
        $this->metaData = $metaData;
    }
}

abstract class Mapper extends BaseMap{
    private $map;

    public function setMap($map) {
        $this->map = $map;
    }

    public function parseData($dataRow) {
        $metaData = $this->getMetaData();
        $parsedDataRow = [];

        foreach($dataRow as $columnName => $columnValue) {
            if(isset($metaData[$columnName]))
                $parsedDataRow[$metaData[$columnName]] = $columnValue;
        }

        return $parsedDataRow;
    }
}

class MapA extends Mapper {
    protected $metaData = [
        'backField1' => 'frontField1',
        'backField2' => 'frontField2'
    ];
}

class MapB extends Mapper {
    protected $metaData = [
        'backFieldA' => 'frontFieldA',
        'backFieldB' => 'frontFieldB'
    ];
}

/* i think the benifits speak for them selfs */
// less code
// less objects
// clean and readable
// easy to use
$mapA  = new MapA();
$mapA->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']);

$mapB  = new MapB();
$mapB->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why is entangling injectable with class that uses it a bad practice?

Body:
I have had this argument for a while, because I have noticed some people prefer "readable" code over properly structured one. So in the example I am showing, basically I have this Mapper class in which different Mappable instances are injected and the Mapper uses the instances to know how to map some data. The question here is, why is it a bad practice to do so. I suspect that the problems are: the method is static, the factory is in the wrong class, making the Mapper hard coupled to the Map classes.

```<code>interface Mappable {
    public function getMetaData();
    public function setMetaData(array $metaData);
}

class BaseMap implements Mappable {
    protected $metaData = [];

    public function getMetaData() {
        return $this->metaData;
    }

    public function setMetaData(array $metaData) {
        $this->metaData = $metaData;
    }

    /**
     * Possible Code Smell
     */
    public static function getNewMapper() {
        return new Mapper(new static);
    }
}

class MapA extends BaseMap {
    protected $metaData = [
        'backField1' => 'frontField1',
        'backField2' => 'frontField2'
    ];
}

class MapB extends BaseMap {
    protected $metaData = [
        'backFieldA' => 'frontFieldA',
        'backFieldB' => 'frontFieldB'
    ];
}

class Mapper {
    private $map;

    public function __construct(Mappable $map) {
        $this->setMap($map);
    }

    public function setMap(Mappable $map) {
        $this->map = $map;
    }

    public function parseData($dataRow) {
        $metaData = $this->map->getMetaData();
        $parsedDataRow = [];

        foreach($dataRow as $columnName => $columnValue) {
            if(isset($metaData[$columnName]))
                $parsedDataRow[$metaData[$columnName]] = $columnValue;
        }

        return $parsedDataRow;
    }
}

// Probably correct
$mapper = new Mapper(new MapA());
print_r($mapper->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']));

$mapper->setMap(new MapB());
print_r($mapper->parseData(['backFieldA' => 'fooA', 'backFieldB' => 'barB']));

// Possible Code Smell
print_r(MapA::getNewMapper()->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']));
print_r(MapB::getNewMapper()->parseData(['backFieldA' => 'fooA', 'backFieldB' => 'barB']));
</code>```

UML class diagram:

Body:
The other problem i see with your code is your inheritance is making contracts with classes it should not need to and is really breaking all oop practices.  This approach allows for less code and cleaner code but also follows the convention of grouped functionality and multiple inheritance.

interface Mappable {
    public function getMetaData();
    public function setMetaData(array $metaData);
}

abstract class BaseMap implements Mappable {
    protected $metaData = [];

    public function getMetaData() {
        return $this->metaData;
    }

    public function setMetaData(array $metaData) {
        $this->metaData = $metaData;
    }
}

abstract class Mapper extends BaseMap{
    private $map;

    public function setMap($map) {
        $this->map = $map;
    }

    public function parseData($dataRow) {
        $metaData = $this->getMetaData();
        $parsedDataRow = [];

        foreach($dataRow as $columnName => $columnValue) {
            if(isset($metaData[$columnName]))
                $parsedDataRow[$metaData[$columnName]] = $columnValue;
        }

        return $parsedDataRow;
    }
}

class MapA extends Mapper {
    protected $metaData = [
        'backField1' => 'frontField1',
        'backField2' => 'frontField2'
    ];
}

class MapB extends Mapper {
    protected $metaData = [
        'backFieldA' => 'frontFieldA',
        'backFieldB' => 'frontFieldB'
    ];
}

/* i think the benifits speak for them selfs */
// less code
// less objects
// clean and readable
// easy to use
$mapA  = new MapA();
$mapA->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']);

$mapB  = new MapB();
$mapB->parseData(['backField1' => 'foo1', 'backField2' => 'bar1']);

OwnerDisplayName: jgetner


问:
Simultaneous purchase in online shop bypassing limited offer
Our client sells several products in an online shop (our software) for a especially low price on the first purchase. Further purchases of each product will fallback to the regular price.

E.g. product costs 10 EUR on the first purchase (quantity fixed to 1) and 20 EUR each on the next purchases (any quantity).

To prevent customers playing tricks and attempting to order products more than once, we compare e-mail, name/address before accepting any order. Although there are still ways to bypass this, we block most naive attempts. Thus customers usually order once and never come back (that's fine, it's solely purpose is product promotion).

However, we just encountered a case where a customer tricked our system. But first, let me explain how our checkout works: When hitting the "buy button", we generate an unique transaction with all order details and redirect the customer to the payment gateway (e.g. PayPal Standard). As soon as we receive a valid and successful payment notification from the payment service provider (e.g. PayPal IPN), this transaction is converted to an actual order. Since the ordered products are now considered purchased, we would block further attempts to purchase them for the lower price.

The said customer did the following to trick the validation: He opened a second browser tab of the summary page with "buy button". He pressed the "buy button" in each tab resulting in two browser tabs (1st tab with transaction ID 1234 and 2nd tab with transaction ID 1235 - same session). The customer then paid for both transactions (e.g. on PayPal) and thus successfully generated two orders with the same products for the low price.

While it is possible to detect such a case or even deny the second purchase here (additional validation after payment notification), we still would need to deal with the money paid by the customer. Is there any technical way to prevent a simultaneous purchase to begin with?

答:
You say:

When hitting the "buy button", we generate an unique transaction with all order details and redirect the customer to the payment gateway

So why wouldn't you check the customers second purchase against this transaction that you have in your database. Even if it's pending and waiting for the payment it still could be used to block any further orders. At least until the customer either cancels this transaction or it times out.

If you don't store this transaction iun the database you should do so and add a flag like "pending".


问:
Web Forms and MVC in the same web project
I'm working in a large legacy project which was build with ASP.NET Web Forms and the idea to add in the MVC libraries to the same project has been tossed around.  I know that this is possible (there are plenty of articles available), but I'm wondering if/why this is/is not recommended by anyone who has done something similar.

The idea is that we could build new areas of the application with the newer MVC pattern and keep the legacy pages running as they always have.

EDIT:  To clarify, we are not considering the MVP pattern as that is already being used in some parts of this project but doing something similar to what is described in this article: https://www.simple-talk.com/dotnet/asp.net/mixing-web-forms-and-asp.net-mvc/

答:
This isn't a bad way to go about rewriting an application. This would be particularly useful for a long term rewrite happening in phases:

Add a "test project" that utilizes CodedUI tests (or Watin or Selenium) to test the WebForms application through the browser. You could also use SpecFlow to define your test cases. I've used this to great affect on a WebForms application.

After you have good test coverage of the WebForms application, you can begin the next phase of refactoring: Moving common components into a separate class library. This is where your models and data access layer could be created. You can add a reference to this library to your WebForms applications. The tests you wrote in phase 1 make sure you don't break existing business rules

Port functionality over to your MVC application, modifying your tests to use the MVC app not the WebForms app.

Steps 1 and 2 could be tackled simultaneously. You can even start on Step 3 once you have an entire feature tested, and its common components are decoupled from the WebForms application.

Split the work out into main features. Once a feature is supported in the MVC application, shut it down in the WebForms application. It will eventually become a hollowed out husk of its former self until you can remove the code all together.


答:
This is hard to prevent, so your best attempt may be to display the customer always the full price (and let him transfer the full money), but display an additional notice under the price that he will get a refund afterwards if it turns out that his purchase was the first. So he may get this message in each browser tab twice, but you don't guarantee him that he will get the refund twice, only tell him that he may gets the money back. This puts you in the situation where you can check what the customer really purchased afterwards, and send him the correct amount of money back when you know for sure what he ordered.

I understand that this may not be ideal since it will make the whole money transfer more complicated, and you need a payback channel for each payment method, but I actually don't see how to solve this differently in a manner where you can be sure you won't get tricked.

Title: Simultaneous purchase in online shop bypassing limited offer

Body:
Our client sells several products in an online shop (our software) for a especially low price on the first purchase. Further purchases of each product will fallback to the regular price.

E.g. product costs 10 EUR on the first purchase (quantity fixed to 1) and 20 EUR each on the next purchases (any quantity).

To prevent customers playing tricks and attempting to order products more than once, we compare e-mail, name/address before accepting any order. Although there are still ways to bypass this, we block most naive attempts. Thus customers usually order once and never come back (that's fine, it's solely purpose is product promotion).

However, we just encountered a case where a customer tricked our system. But first, let me explain how our checkout works: When hitting the "buy button", we generate an unique transaction with all order details and redirect the customer to the payment gateway (e.g. PayPal Standard). As soon as we receive a valid and successful payment notification from the payment service provider (e.g. PayPal IPN), this transaction is converted to an actual order. Since the ordered products are now considered purchased, we would block further attempts to purchase them for the lower price.

The said customer did the following to trick the validation: He opened a second browser tab of the summary page with "buy button". He pressed the "buy button" in each tab resulting in two browser tabs (1st tab with transaction ID 1234 and 2nd tab with transaction ID 1235 - same session). The customer then paid for both transactions (e.g. on PayPal) and thus successfully generated two orders with the same products for the low price.

While it is possible to detect such a case or even deny the second purchase here (additional validation after payment notification), we still would need to deal with the money paid by the customer. Is there any technical way to prevent a simultaneous purchase to begin with?


问:
What's a good Programming Metaphor?
I am referring to explaining to the non-programmer what programming is. I made sure to search for similar questions before creating this one, but the few ones I did find seemed to dodge the question, and I specifically would like to see some metaphors or analogies. I personally find it easier to explain something technical to someone through the use of metaphors or analogies.

The reason I'm interested in this is because many people encounter the work of a programmer on a daily basis, but if you ask the average person what a programmer is or does, they don't really know. This leads to certain situations of misunderstanding (ex. "[...] but I thought you were good with computers!")

I really would like to find the best one out there. I would like to be able to easily explain to someone what my career choice is about. Of course, at least the general idea.

I personally don't have a solid one, but I have long thought about it and I have usually gravitated towards the 'language' metaphor, where we happen to know a language that computers understand, and therefore we are able to tell computers what to do, or "teach" them, to solve our problems.

For example:

Imagine that in an alternate reality, humanoid robots with artificial intelligence exist, and some people are able to communicate with them through a common language, which is a variation of English. These people who can communicate with the robots are able to teach them how to solve certain problems or do certain tasks, like doing our chores.

Well, although robots like that don't exist yet, programmers of our time are like those people, but instead of communicating with the robots, they communicate with computers. Programmers "teach" the computers how to perform certain tasks or solve certain problems by means of software which they create by using this "common language".

Programmers and this "common language" are what give us things like email, websites, video games, word processors, smart phones (to put it simply), and many other things which we use on a daily basis.

I don't mean to put programming on the throne or anything, it's just the best metaphor I could come up with.

I'm sure someone will find some issue with this one, it's probably a bit contrived, but then again that's why I'm asking this question.

答:
Not very good analogy but when people tell me to fix their machine I say
"I am the guy that designs the cars. I am not the mechanic!"</p>

ContentLicense: CC BY-SA 2.5

Title: What's a good Programming Metaphor?


问:
Is it good practice to rely on headers being included transitively?
I'm cleaning up the includes in a C++ project I'm working on, and I keep wondering whether or not I should explicitly include all headers used directly in a particular file, or whether I should only include the bare minimum.

Here's an example, Entity.hpp:

```<code>#include "RenderObject.hpp"
#include "Texture.hpp"

struct Entity {
    Texture texture;
    RenderObject render();
}
</code>```

(Let's assume that a forward declaration for RenderObject is not an option.)

Now, I know that RenderObject.hpp includes Texture.hpp - I know that because each RenderObject has a Texture member. Still, I explicitly include Texture.hpp in Entity.hpp, because I'm not sure if it's a good idea to rely on it being included in RenderObject.hpp.

So: Is it good practice or not?

答:
Good practice is to not worry about your header strategy as long as it compiles.

The header section of your code is just a block of lines that nobody should even look at until you get an easily resolved compile error.  I understand the desire for 'correct' style, but neither way can really be described as correct.  Including a header for every class is more likely to cause annoying order-based compile errors, but those compile errors also reflect problems that careful coding could fix (though arguably they're not worth the time to fix).

And yes, you will have those order-based problems once you start getting into friend land.

You can think of the problem in two cases.

Case 1: You have a small number of classes interacting with each other, say less than a dozen.  You regularly add to, remove from, and otherwise modify these headers, in ways that may affect their dependencies on each other.  This is the case which your code example suggests.

The set of headers is small enough that it is not complicated to solve any problems that crop up.  Any difficult problems are fixed by rewriting one or two headers.  Worrying about your header strategy is solving problems which do not exist.

Case 2: You have dozens of classes.  Some of the classes represent the backbone of your program, and rewriting their headers would force you to rewrite/recompile a great amount of your code base.  Other classes use this backbone to accomplish things.  This represents a typical business setting.  Headers are spread across directories and you can't realistically remember the names of everything.

Solution: At this point, you need to think of your classes in logical groups and collect those groups into headers which stop you from having to #include over and over.  Not only does this make life simpler, it is also a necessary step to taking advantage of precompiled headers.

You end up #includeing classes you don't need but who cares?

In this case, your code would look like...

```<code>#include <Graphics.hpp>

struct Entity {
    Texture texture;
    RenderObject render();
}
</code>```

Body:
Good practice is to not worry about your header strategy as long as it compiles.

The header section of your code is just a block of lines that nobody should even look at until you get an easily resolved compile error.  I understand the desire for 'correct' style, but neither way can really be described as correct.  Including a header for every class is more likely to cause annoying order-based compile errors, but those compile errors also reflect problems that careful coding could fix (though arguably they're not worth the time to fix).

And yes, you will have those order-based problems once you start getting into friend land.

You can think of the problem in two cases.

Case 1: You have a small number of classes interacting with each other, say less than a dozen.  You regularly add to, remove from, and otherwise modify these headers, in ways that may affect their dependencies on each other.  This is the case which your code example suggests.

The set of headers is small enough that it is not complicated to solve any problems that crop up.  Any difficult problems are fixed by rewriting one or two headers.  Worrying about your header strategy is solving problems which do not exist.

Case 2: You have dozens of classes.  Some of the classes represent the backbone of your program, and rewriting their headers would force you to rewrite/recompile a great amount of your code base.  Other classes use this backbone to accomplish things.  This represents a typical business setting.  Headers are spread across directories and you can't realistically remember the names of everything.

Solution: At this point, you need to think of your classes in logical groups and collect those groups into headers which stop you from having to #include over and over.  Not only does this make life simpler, it is also a necessary step to taking advantage of precompiled headers.

You end up #includeing classes you don't need but who cares?

In this case, your code would look like...

#include <Graphics.hpp>

struct Entity {
    Texture texture;
    RenderObject render();
}


问:
The most effective arguments in favor of improving code quality, for a manager
My employer's legacy system started off (in 1997) as very structured procedural code (with a smidgeon of OO), and it was luckily one of the 10% of software projects that was successful. It may look a little antequated today, but at least it is structured and provided a framework to hang extensions upon.

Fast forward to the late 2000's and developers not connected with the original architects have bit by bit extended the system in an ad hoc way with no architecture, just making decisions as they went along, going with what seemed to make sense to them at the time. They also abandoned any naming or coding conventions. To over-simplify, they never make a class, never make anything for re-use, and the only consideration is: "will it break what is already there?" which puts a damper on more innovative approaches. There is still lots of VB6 code.

These developers are still there, and they are entrenched, and can patch the system, or do things allow by the original architects, very fast.

However, since there is zero code reuse, they have no building blocks with which to build an entirely new system, so they can't do anything really special or novel for a prospective client, even a giant one like Sams Club.

I recall there were some really good arguments for improving code quality, for example, by using OO methodology, in money terms that would get an executive's attention, but I can't recall where I saw it. It has been a while. I intuitively sense that gathering all functionality into a class provides the most flexibility and maintainability but I don't have any ammo.

Some of the thoughts I'm up against include: The system seems to be working "just fine". So why should we rock the boat with something like a "quality program"? The current  developers love it the way it is, so they don't want to do anything to improve their code or the quality of the architecture. They know every one of the 73 places a certain quantity is referenced. Who needs it? T-Sql doesn't need to be compiled! Copy and pasting the same code localizes bugs to that particular copy.

EDIT:

It was unclear what I was asking, huh? Well, the answer accepted contains a comment that has a link (http://blog.codinghorror.com/the-big-ball-of-mud-and-other-architectural-disasters/) that was exactly what I was looking for, so I marked as answer. So, someone, perhaps several people, inherently knew what I was asking anyway. If you read the article sited, you'll see that actually what I'm going thru here is common. I am very much not alone in this, which makes me feel better. :-)

答:
You original question seemed to reflect a misconception - one of top 10 false assumptions about OO: the belief that object orientation will imply more code reuse and less duplicated code.

That is a fallacy!

If you have devs who care for DRY code, care for reuse and who have learnt and understood OO principles, they can use the latter to build better, more reusable software. But it never works the other way round - just introducing some object orientation to a team of people who do not care for the things I mentioned before will not change any of their bad habits.

So I guess what you are really after is something like a quality offensive to work actively against the famous big-ball-of-mud architecture. Note that the article behind this link does not contain the word "object orientation". Actually, it also does not contain any arguments in terms of money (but I guess the comparisons and pictures used there are nonetheless understandable for most managers).


问:
multiple comparison sorting
I have a set of songs where I want to sort them by a particular quality. In order to do this (by crowdsourcing) I will present users with a comparison between two songs. The user will then choose which one ranks higher.

What algorithm can I use to weight the different comparisons? Given that I'll have a data set of comparisons between two points such as...

```<code>[ A >= B : 2
  A <= B : 0
  A >= C : 1
  A <= C : 4
  ...
   ( two dimensional array of size 2 * |songs - 1|^2 )
  ...
]
</code>```

答:
One possible formalization is as a longest path problem. Construct a directed graph in which nodes are labeled with songs, and for each ordered pair of songs (A, B) there is a weighted edge A -> B with weight equal to the number of votes for A  B, then the consensus is that A < B.

Unfortunately, this problem is NP-hard unless the graph is acyclic (ie. no inconsistent rankings in your database). You may still be able to solve it in a reasonable amount of time depending on how many songs there are.

Title: multiple comparison sorting

Body:
One possible formalization is as a longest path problem. Construct a directed graph in which nodes are labeled with songs, and for each ordered pair of songs (A, B) there is a weighted edge A -> B with weight equal to the number of votes for A < B. Then the longest simple path is a total order that agrees with the maximum number of votes. If the longest path contains the edge A -> B, then the consensus is that A < B.

Unfortunately, this problem is NP-hard unless the graph is acyclic (ie. no inconsistent rankings in your database). You may still be able to solve it in a reasonable amount of time depending on how many songs there are.


答:
The problem doesn't require an exact solution.  And opinions are not an exact mesure anyway.  You could simply count +1 every time a song is preferred and -1 every time it is not preferred.

```<code>              A   B   C
A >= B : 2   +2  -2
A <= B : 0    0   0
A >= C : 1   +1      -1
A <= C : 4   -4      +4
             ----------
             -1  -2  +3
</code>```

This would give the order C > A > B.

Title: multiple comparison sorting

Body:
I have a set of songs where I want to sort them by a particular quality. In order to do this (by crowdsourcing) I will present users with a comparison between two songs. The user will then choose which one ranks higher.

What algorithm can I use to weight the different comparisons? Given that I'll have a data set of comparisons between two points such as...

```<code>[ A >= B : 2
  A <= B : 0
  A >= C : 1
  A <= C : 4
  ...
   ( two dimensional array of size 2 * |songs - 1|^2 )
  ...
]
</code>```

Body:
The problem doesn't require an exact solution.  And opinions are not an exact mesure anyway.  You could simply count +1 every time a song is preferred and -1 every time it is not preferred.

              A   B   C
A >= B : 2   +2  -2
A <= B : 0    0   0
A >= C : 1   +1      -1
A <= C : 4   -4      +4
             ----------
             -1  -2  +3

This would give the order C > A > B.


问:
Cobol programs and copybooks versioning
in java we have ivy, maven and others for handling library dependencies. For example I tell ivy that my program uses a framework-jar version 1.0 and ivy makes sure, that my program gets this jar when being compiled. When there comes an update and the framework-jar is now available in version 1.1, then my program still gets the version 1.0. I can however tell ivy that another program of mine should take the newer version 1.1.

Are there similar mechanisms in the cobol environments so that i can make sure my cobol program A uses copybook C in version 1.0 and my cobol program B uses copybook C in version 1.1?

答:
Start with WIDGET-UPDATE, clone it to create WIDGET-UPDATE-V1, and change COBOL program C to PERFORM WIDGET-UPDATE-V1.

I suppose one could partially satisify the requirement by hardcoding the version as a "parameter".

In Program A

```<code>MOVE '1' TO WU-VERSION.
PERFORM WIDGET-UPDATE.
</code>```

In Program B

```<code>MOVE '1.1' TO WU-VERSION.
PERFORM WIDGET-UPDATE.
</code>```

In CopyBook C

```<code>EVALUATE WU-VERSION
    WHEN '1'
        PERFORM WIDGET-UPDATE-V1
    WHEN '1.1'
        PERFORM WIDGET-UPDATE-V1-1
    WHEN OTHER
        PERFORM INVALID-VERSION
END-EVALUATE.
</code>```

Title: Cobol programs and copybooks versioning

Body:
Start with WIDGET-UPDATE, clone it to create WIDGET-UPDATE-V1, and change COBOL program C to PERFORM WIDGET-UPDATE-V1.

I suppose one could partially satisify the requirement by hardcoding the version as a "parameter".

In Program A

MOVE '1' TO WU-VERSION.
PERFORM WIDGET-UPDATE.

In Program B

MOVE '1.1' TO WU-VERSION.
PERFORM WIDGET-UPDATE.

In CopyBook C

EVALUATE WU-VERSION
    WHEN '1'
        PERFORM WIDGET-UPDATE-V1
    WHEN '1.1'
        PERFORM WIDGET-UPDATE-V1-1
    WHEN OTHER
        PERFORM INVALID-VERSION
END-EVALUATE.


问:
Freelance web development vs. design
Do web design freelancers (I'm thinking individuals, not companies) typically do all development and design work themselves? What are the options for those with a strong base in back-end web development but less with web design, color schemes, layouts, graphic design, etc.?

答:
I typically get all of my design work sub-contracted. That is, I'll hire a designer to build a photoshop version of the site, usually getting it 90% of the way there and then either get someone to cut up that design into HTML & CSS, or do that myself (depending on a number of factors).

There are many options for getting the initial design. I tend to use the same designer that I've used in the past, but you can use sites like 99designs.com or more generic freelance sites like elance.com to find designers. I would tend to prefer the designer-specific 99designs.com, they're more expensive but the quality is generally higher.

In the past, I've also sub-contracted out the HTML/CSS cutting, but I find that is more hit-and-miss than the designs themselves. I usually prefer to do the cutting myself, since I can tailor the HTML/CSS to fit better with the server-side generation of the HTML. I find that many companies which provide HTML/CSS cutting don't take tweaking or modifications into account and making changes to the layout or slight tweaks later on can be very painful. I've been burnt by that often enough - it's ended up costing me more time tweaking a badly cut design than if I had just done the whole thing from scratch - that I don't even bother much any more.

Title: Freelance web development vs. design


问:
Modular Web App Network Architecture
Assuming that I am dealing with dedicated physical servers or VPSs, is it conceivable and does it make sense to have distinct servers setup with the following roles to host a web application?

Reverse Proxy

Web server

Application server

Database server

Specific points of interest:

I am confused how to even separate the web and application servers.  My understanding was that such 3-tier architectures were feasible.

It is unclear to me if the app server would reside directly between the web and database server, or if the web server could directly interact with the database as well.  The app server could either do the computational heavy-lifting on behalf of the app server or it could do heavy-lifting plus control all of the business logic (as implied in the diagram above, thus denying the web server of direct database access).

I am also unsure what role the reverse proxy (ex. nginx) could and should fulfill as a web server, given the above mentioned setup.  I know that nginx has web server features.  But I do not know if it makes sense to have the reverse proxy be its own VPS, given that the web server–in theory–would be separate from the app server.

答:
you can think of App Servers as a sort of super version of JDBC or ActiveRecord or whatever it is you use.  Some applications won't need that separation, and if this is your first pass, as mentioned, don't worry about it.  However, if you find that the logic responsible for interacting with the database is getting very complex, it can be useful to split that out into its own service.  This is pretty much always done in Big Data environments since the logic around programming the database is so complex and involved.

If all you have is a simple web-app that doesn't need anything more complex than MySQL or Postgres, I wouldn't worry about the App Server just yet.  If you are using a web decent framework for the web server (such as Play, Django, Rails, etc.), the code will be modular enough that swapping out the DAO layer for a REST/HTTP layer to communicate with a new App Server shouldn't be too hard.

It's already been mentioned that the web server can double as the reverse proxy, as well.  Again, if you find that this gets sufficiently complex down the road to justify giving that logic it's own box, by all means.  Just be mindful of the fact that this is a possible direction the app could go in the future when you are programming things so that you don't end up needing to untangle unmodular code in order to break out a dedicated proxy server.

Title: Modular Web App Network Architecture


问:
Why do people disable JavaScript?
I asked a question yesterday Should I Bother to Develop For JavaScript Disabled?. I think the consencus is: Yes, I should develop for JavaScript Disabled. Now I just want to understand why users disable JS. It seems many developers (I guess people who answered the questions are developers) disable JS. Why is that. Why do users disable JS? For security? Speed? or what?</p>

答: Because trusting somebody to write a funny comic strip every morning and trusting somebody to run arbitrary Turing-complete code on my computer are two very different things.

Title: Why do people disable JavaScript?


问:
Should you version web applications?
I've recently had a discussion with a coworker about versioning web applications.

I don't think you need it at all, and if you just want a sanity check to confirm your latest release is live, I think a date (YYMMDD) is probably good enough.

Am I off base?  Am I missing the point?  Should I use web application version numbers

答:
From your question it is clear that you have in mind a simple web application

Only accessible by a Web GUI and not by a Web(-service) API. If you have users accessing the application using an API you need to version it. If you change the API you break clients, so you need to maintain different version of the API at the same time.

Only one instance running at the time. Even if you have only the web guy, if you have more installation you need to know which customer is running which version.

With acceptable down-time for upgrade of live version. There is a possibly huge problem which is the database. Important changes with newer versions come with changes in the underlying structure of the data. If you have only one version running at the time you will probably have to turn off the old version, upgrade the database, and turn on the new version. Which results in application down-time. This can be acceptable depending on the number and kind of users.

Title: Should you version web applications?


问:
OOP CLI menu structure organization?
This problem has kept me from pursuing a project I'm working on because it influences the entire structure of the application. This question has been briefly touched on here, but I feel that it wasn't seen by many people and therefore wasn't very well answered.

I'm working on an application in charge of navigating and manipulating a binary search tree. This application is controlled through a selection menu, with some options leading to submenus. The most hack-ish approach to this problem is something like this:

```<code>int main(int argc, char *argv[])
{
    // Create the object using the data in the file at path argv[1].
    BinarySearchTree tree(argv[1]);

    bool exit = false;
    while (!exit) {
        // Print the menu out here with std::cout statements.
        // This always adds several lines that don't do much.

        // Store the users input in a variable here.
        // Coding a way that ensures something valid is input adds
        // many more lines of clutter.

        // If-elseif-else or switch statement here. More complexity with more
        // submenus that look exactly like this here. You get how complex
        // this will get.
    }
}
</code>```

Anyone who wants to type good code doesn't want their main function to be this long and messy. Breaking it into other functions sitting in my main file doesn't really help much either, it's still messy and not very object-oriented. A possible solution would be to put each menu into their own class like this.

```<code>int main(int argc, char *argv[])
{
    BinarySearchTree tree(argv[1]);
    MainMenu main_menu;
    main_menu.run();
}
</code>```

Definitely the cleanest main method, but not a viable option since my tree object can no longer be accessed from within the MainMenu methods, and I definitely don't want to pass it around endlessly within my class methods since that'd be terrible style. So finally some middle ground I came up with was like this.

```<code>int main(int argc, char *argv[])
{
    BinarySearchTree tree(argv[1]);

    MainMenu main_menu();
    bool exit = false;
    while (!exit) {
        unsigned long prompt = main_menu.prompt();

        // The switch statement here. Still a lot of complexity I don't like
        // because this can go on for quite a while depending on how deep my
        // submenus go or how much I need to do for specific commands.
    }
}
</code>```

Ok, all my sample code is out of the way. I don't like any of them, and I haven't found any truly better solutions on the internet. I'm an undergrad, so I don't have any practical experience in this. Is there some widely accepted best-practice in the industry that I don't know about? How would you approach this personally? Remember, this is being implemented in C++ so I'm trying to be as object-oriented as possible. However, if there's a functional way you know of that works really well that you'd like to share, I'd be open to it.

答:
If you need some data created somewhere in another class, you have to pass it. That is not bad style, there is nothing "messy" in it, that is just the way how data is to be used in a program. Ideally you pass it only once in the constructor:

```<code> MainMenu main_menu(tree);
</code>```

If that tree is needed in lots of places inside the class MainMenu, you store just a reference to it in a member variable of MainMenu, for example

```<code> class MainMenu
 {
     BinarySearchTree &m_tree;

     MainMenu(BinarySearchTree &tree)
     : m_tree(tree)
     {
     }

     void run()
     {
         // do things with m_tree here, maybe pass it to a different sub menu
     }
  }
</code>```

This avoids the need for "endless passing within your classes methods", as you wrote.

You may consider not to "interweave" the access to you binary tree too much with the menu code. But for telling you if and how it is possible one has to look at the part of the program which actually deals with the tree. So the only guideline I can give you so far is put the actual operations on the tree into functions which are separated from your menu classes (maybe as member functions of your BinarySearchTree, maybe member functions of something like a TreeManipulator class, depends on how those operations look like).

Title: OOP CLI menu structure organization?

Body:
If you need some data created somewhere in another class, you have to pass it. That is not bad style, there is nothing "messy" in it, that is just the way how data is to be used in a program. Ideally you pass it only once in the constructor:

 MainMenu main_menu(tree);

If that tree is needed in lots of places inside the class MainMenu, you store just a reference to it in a member variable of MainMenu, for example

 class MainMenu
 {
     BinarySearchTree &m_tree;

     MainMenu(BinarySearchTree &tree)
     : m_tree(tree)
     {
     }

     void run()
     {
         // do things with m_tree here, maybe pass it to a different sub menu
     }
  }

This avoids the need for "endless passing within your classes methods", as you wrote.

You may consider not to "interweave" the access to you binary tree too much with the menu code. But for telling you if and how it is possible one has to look at the part of the program which actually deals with the tree. So the only guideline I can give you so far is put the actual operations on the tree into functions which are separated from your menu classes (maybe as member functions of your BinarySearchTree, maybe member functions of something like a TreeManipulator class, depends on how those operations look like).


问:
Given a number which is power of 2, check if it is even power or odd power
I am given a number n , which is always a power of 2.
I want to check whether n is odd power of 2 or even power of 2.

For example: n=4 , ans= even
n=8, ans=odd (because 8 is 2^3)
n=1024 , ans=even.

Can I do it using bitwise operations/ or some faster method.

答:
If it is known that n is indeed a power of 2, then only one bit in the integer can ever be lit.

If the index of that bit is even, then your answer is even (assuming bit indices are 0-based).

For negative numbers, you may want to use the absolute value.

And obviously, the assumption is that we are dealing with 32-bit or 64-bit integers, not floating point numbers.


问:
Should I use composition or inheritance for sharing configuration items?
I'm working on a fairly new project where I'd like to share some config items used by a JavaScript plugin. Specifically, the project is using jQuery dataTables and I want to find a good way of sharing config items.

At the moment, the code I've been given is fairly simple. It is roughly equivalent to:

```<code>// It might not be super-essential to read this

function TableSuperClass(tableElement, moreOptions) {
    var options = {
         pagination: true,    // turn on pagination
         iDisplayLength : 50, // pages are fifty rows long
         lengthChange: false, // stop users changing length of pages
         searching : false    // disables searching
    };

    jQuery.extend(options, moreOptions); // merge moreOptions into options
    jQuery(tableElement).DataTable(options); // we create a table with the extended options

    // This is a super-handy method we'd like to use everywhere
    this.repopulate = function usefulRepopulateFunction() {...};
}

function ObjectOwningTable() {
    // this object does other things too

    this.table = TableSuperClass({
         // various column mappings for a particular table type and
         // what to order the table on
         columns : [...],
         // implements row highlighting, partly based on column mappings
         fnRowCallback : function() {...}
    });
}

function AnotherObjectOwningTable() {
    // this object does other things too

    this.table = TableSuperClass({
         // various column mappings for a different type of table, switched
         // based on some logic inside this class
         columns : someTest ? [...] : [...],
         // implements ordering a different way
         aDesc : [...] // aDesc is a legacy API call that lets you specify the col to order on
    });

}
</code>```

The problem is that I now have another sort of table. It is used in a print view. It has the same column mappings as ObjectOwningTable, it needs the super-convenient repopulate method and disabled searching from TableSuperClass, but it doesn't have pagination, as a printout has to show the whole data set.

I can think of two basic solutions:

Solve the problem with inheritance. Make TableSuperClass provides the handy repopulate interface and disabled searching, then a subclass with pagination, then call that in ObjectOwningTable and AnotherObjectOwningTable. For my print table, I call TableSuperClass with the same column mappings as used in ObjectOwningTable (maybe I extract them to a global constant or something).

Solve the problem with composition. I have a single DynamicTable that provides just the repopulate interface, then pass in a list of plain objects that are applied to the options in order. These plain objects all live on an enum somewhere, so I can see how they might clash as I write them, and allow me to mix-and-match functionality further down the line.

So, at the consumer level, the first solution would end up looking like

```<code>function ObjectOwningTable() {
    this.table = PagedTable(FOO_REPORT_COLUMN_MAPPINGS);
}

function AnotherObjectOwningTable() {
    this.table = PagedTable(someTest? BAR_COLUMN_MAPPINGS : BAZ_COLUMN_MAPPINGS);
}

function PrintObjectOwningTable() {
    this.table = TableSuperClass(FOO_REPORT_COLUMN_MAPPINGS);
}
</code>```

Whereas the latter would look like

```<code>function ObjectOwningTable() {
    this.table = DynamicTable([
        DATA_TABLES_OPTIONS.pagingFixedAtFiftyRows,
        DATA_TABLES_OPTIONS.disableSearching,
        DATA_TABLES_OPTIONS.fooColumnsAndHighlighting
    ]);
}

function AnotherObjectOwningTable() {
    var columnMappings = someTest ? DATA_TABLES_OPTIONS.barColumnMappings : DATA_TABLES_OPTIONS.bazColumnMappings;
    this.table = DynamicTable([
       DATA_TABLES_OPTIONS.pagingFixedAtFiftyRows,
       DATA_TABLES_OPTIONS.disableSearching,
       columnMappings
    ]);
}

function PrintObjectOwningTable() {
    this.table = DynamicTable([
       DATA_TABLES_OPTIONS.disableSearching,
       DATA_TABLES_OPTIONS.fooColumnsAndHighlighting,
       DATA_TABLES_OPTIONS.disableSortingControls
    ]);
}
</code>```

I'm not sure what to choose. The inheritance approach feels very problematic. It seems very inflexible, and I can see a lot of ways for future developers to 'trap' functionality in particular class taxonomies. I also think that long inheritance chains are harder to reason about than flat structures. But the compositional approach is a bit more verbose, and I think my co-workers might object to the repetition. Yet I think that mixing and matching is really handy.

There is a third option, which is to create a subclass of DynamicTable that binds the pagingFixedAtFiftyRows and disableSearching options, and is then called by the objects that use it, passing in their peculiar column mappings. But I wonder if this makes things more complicated, using both subclasses and mixins. I also wonder if it creates the temptation for other developers to add functionality to the subclass when they should really try and create mixins.

What would you recommend?

答:
Given just the two possibilities you present, I think the first, inheritance, solution is better, even though I generally don't think inheritance solutions are better.

If I understand the code correctly, you second solution involves just one type DynamicTable that has a whole slew of booleans in it to customize its behavior. This means that anytime someone needs a table with different behavior, they will have to go into DynamicTable to add yet another boolean and conditionally change the tables behavior based on the new boolean.

Better, I think, would be to follow the Open/Closed Principle. DynamicTable should employ judicious use of the Strategy pattern such that your various other types can customize its behavior by injecting blocks of code into it, rather than simply setting booleans.

For example, you have the notion of pagingFixedAtFiftyRows. Presumably, you also have the notion of paging not being fixed at fifty rows, and that also opens the door to the idea of paging being fixed, but at something other than fifty rows. Expressing the notion of having pagingFixedAtFIftyRows as a boolean is kind of silly in this regard. At minimum, it should be an integer (where 0 would mean paging is not fixed.)

Another example, you have the notion of disableSearching. Presumably, in the DynamicTable you have at least one if statement that checks this bool and does something different depending on whether or not it is true. Better would be to have a separate Search Module that contains the conditional code. If a user wants searching, they inject the search module into the table. This also opens the door for them to do other interesting things to filter the output of the table that isn't exactly like searching.

Good luck with whatever solution you decide, but I suggest you look into the Strategy Pattern, you will likely get more ideas http://en.wikipedia.org/wiki/Strategy_pattern


答:
Assuming n is a 32 bit integer:

If n and'ed with x55555555 > 0 then even else odd

Assuming n is a 64 bit integer:

If n and'ed with x5555555555555555 > 0 then even else odd

If you put the mask into hex calculator, that also shows binary, you will see that the mask has all even bits set:

```<code>0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 - 64 bits
or
0101 0101 0101 0101 0101 0101 0101 0101 - 32 bits
</code>```

Title: Given a number which is power of 2, check if it is even power or odd power

Body:
I am given a number n , which is always a power of 2.
I want to check whether n is odd power of 2 or even power of 2.

For example: n=4 , ans= even
n=8, ans=odd (because 8 is 2^3)
n=1024 , ans=even.

Can I do it using bitwise operations/ or some faster method.

Body:
Assuming n is a 32 bit integer:

If n and'ed with x55555555 > 0 then even else odd

Assuming n is a 64 bit integer:

If n and'ed with x5555555555555555 > 0 then even else odd

If you put the mask into hex calculator, that also shows binary, you will see that the mask has all even bits set:

0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 0101 - 64 bits
or
0101 0101 0101 0101 0101 0101 0101 0101 - 32 bits


问:
Quickest sorting algorithm for sorting a low number of integers
I am making a program on my spare time that I want to run as quickly as possible. The program is written in C.

A large set of the procedures operate on pointers to 7 integers that are sorted by their numerical values from high to low.

Up to this point I have used the library function "qsort" to sort my integers. Now when I have finished the rest of the application I want to replace my call to qsort with something quicker.

I want a sorting algorithm to sort a fixed number of 7 integers as fast as possible. Please tell me what you would use and why you think it is best.

I have read about the Big O notation and from what I have found out it only measures how long the algorithm will take according to the number of elements it needs to sort. Does the Big O notation really matter when I only need to sort 7 elements? Can O(n * log n) be faster than a O(n ^ 2) in this case?

"radixsort" seems like a good choice to me but I want to get your opinions too.

The sorting algorithm will be used millions of times and during that time the user of the program has to wait. My program runs almost 10 times slower since I started using qsort (before that I measured it using a hard-coded array).

答:
Take a look at this neat implementation of sorting six integers. According to sorting networks, 16 comparisons are required to sort 7 integers. Here is the code for seven integers:

```<code>    static int sort7(int *d){
#define SWAP(x,y) if (d[y] < d[x]) { int tmp = d[x]; d[x] = d[y]; d[y] = tmp; }
    SWAP(1, 2);
    SWAP(3, 4);
    SWAP(5, 6);
    SWAP(0, 2);
    SWAP(3, 5);
    SWAP(4, 6);
    SWAP(0, 1);
    SWAP(4, 5);
    SWAP(2, 6);
    SWAP(0, 4);
    SWAP(1, 5);
    SWAP(0, 3);
    SWAP(2, 5);
    SWAP(1, 3);
    SWAP(2, 4);
    SWAP(2, 3);
#undef SWAP
}
</code>```

Note that I did not test the code!

Body:
Take a look at this neat implementation of sorting six integers. According to sorting networks, 16 comparisons are required to sort 7 integers. Here is the code for seven integers:

    static int sort7(int *d){
#define SWAP(x,y) if (d[y] < d[x]) { int tmp = d[x]; d[x] = d[y]; d[y] = tmp; }
    SWAP(1, 2);
    SWAP(3, 4);
    SWAP(5, 6);
    SWAP(0, 2);
    SWAP(3, 5);
    SWAP(4, 6);
    SWAP(0, 1);
    SWAP(4, 5);
    SWAP(2, 6);
    SWAP(0, 4);
    SWAP(1, 5);
    SWAP(0, 3);
    SWAP(2, 5);
    SWAP(1, 3);
    SWAP(2, 4);
    SWAP(2, 3);
#undef SWAP
}

Note that I did not test the code!


问:
Smart fallback for line endings in code files?
What do you recommend as a default fallback for line endings if the operating system cannot be determined?

Example

Mac OS up to version 9 uses carriage returns (\r) for line endings. Unix-like systems do line endings with line feeds (\n) and Windows uses two characters (\r\n) to mark a line ending.

What's the best fallback which is most compatible for all mentioned systems when writing code files which are exchanged with developers on different platforms?

答:
I would vote for CRLF:

Windows is still the most widely used OS for personal computing, therefore all other OSs have ways to deal with DOS line endings

The opposite is not necessarily true, not all Windows apps can deal with Unix or Mac line endings

CRLF is also the line ending for all Internet Standards and RFCs, e.g. HTTP, MIME, Usenet, Internet Mail, vCard, iCal etc.


问:
What are the skills you look for when hiring a fresher/newbie for developement?
I really want to ask this questions to my fellow developers here in Programmers.SE because i am hiring freshers for my company.. Even though i know some basic questions that can be asked to a fresher during interview and i want to know,

What are the skills you look for when hiring a fresher/newbie for developement?

答:
The most important qualities a fresher should have is the right attitude and problem solving capabilities. The right attitude can be checked by asking them the questions about the final year project. Check if the person was really involved in the project. See his/her enthusiasm. Check if the person has enthusiasm in programming. Check if he/she has participated in any competition or member of any organization. </p>

<p>Problem solving capabilities can be checked by asking small puzzles which can be solved using hints. More stress should be given on the way how the problem was attacked. This can also be checked by giving small programming assignment (second greatest in an array, finding stream of k consecutive zeros, or Joel's favorite number of set bits in an int) in their favorite language. Again rather than whether he/she knows the problem, the emphasis should be on how he/she is tackling the problem.  </p>

Body:
The most important qualities a fresher should have is the right attitude and problem solving capabilities. The right attitude can be checked by asking them the questions about the final year project. Check if the person was really involved in the project. See his/her enthusiasm. Check if the person has enthusiasm in programming. Check if he/she has participated in any competition or member of any organization.

Problem solving capabilities can be checked by asking small puzzles which can be solved using hints. More stress should be given on the way how the problem was attacked. This can also be checked by giving small programming assignment (second greatest in an array, finding stream of k consecutive zeros, or Joel's favorite number of set bits in an int) in their favorite language. Again rather than whether he/she knows the problem, the emphasis should be on how he/she is tackling the problem.


问:
How should I setup this type to be intuitive?
I have the following types:

```<code>data Bomb = TimedBomb   { bPos :: Point, bPower :: Float, detTime :: Float }

data Enviro = Enviro { bombs :: [Bomb], stuff :: [Picture]}
</code>```

When the TimedBomb timer reaches 0, I need it to explode, damage any enemies within it's blast radius (controlled by bPower), and persist for a few seconds to add to the chance that it will cause damage. To do that, I was thinking of creating another object representing an explosion, then check to see if any enemies are within its bounds. The problem is, I can't think of the best set-up to hold explosions that are taking place. I'm using Haskell's Gloss library, so the entirety of what's being drawn needs to be contained within a single "world" object. What I've thought of:

I could make an explosion a type of Bomb, hold it in bombs in the environment, and map over bombs when I want to check for collisions. That seems like the simplest route, but it would involve possibly doing checks on non-explosion-Bombs, which is inefficient. An explosion isn't really a bomb either; its the end result, so the types don't make intuitive sense.

I could make explosions a separate type, then add another field to Enviro called explosions of type [Explosion]. That makes more sense, but adds another field to Enviro, which already tends to be a cluttered type.

I could be thinking of the whole set-up wrong, and there's a third, more sensical way to go about this.

Any thoughts here would be appreciated

答:
The key to clarity is separation

You should separate the Bomb's constant data from it's mutable state:

```<code>data Bomb
  = Bomb
  { bPos    :: Point
  , bPower  :: Float
  , bState  :: BombState
  }
  deriving (Eq,Read,Show)

data BombState
  = Armed       { detTime :: Float }
  | Discharging { expTime :: Float }
  deriving (Eq,Read,Show)

data Enviro
  = Enviro
  { bombs :: [Bomb]
  , stuff :: [Picture]
  }
  deriving (Eq,Read,Show)

isDischarging (Discharging _) = True
isDischarging  _              = False

exploding :: Enviro -> [Bomb]
exploding = filter (isDischarging . bState) . bombs
</code>```

This would allow you to add more states later such as Disarmed and Inert

```<code>data BombState
  = Armed       { detTime :: Float }
  | Discharging { expTime :: Float }
  | Disarmed    ( remTime :: Float }
  | Inert
</code>```

Body:
The key to clarity is separation

You should separate the Bomb's constant data from it's mutable state:

data Bomb
  = Bomb
  { bPos    :: Point
  , bPower  :: Float
  , bState  :: BombState
  }
  deriving (Eq,Read,Show)

data BombState
  = Armed       { detTime :: Float }
  | Discharging { expTime :: Float }
  deriving (Eq,Read,Show)

data Enviro
  = Enviro
  { bombs :: [Bomb]
  , stuff :: [Picture]
  }
  deriving (Eq,Read,Show)

isDischarging (Discharging _) = True
isDischarging  _              = False

exploding :: Enviro -> [Bomb]
exploding = filter (isDischarging . bState) . bombs

This would allow you to add more states later such as Disarmed and Inert

data BombState
  = Armed       { detTime :: Float }
  | Discharging { expTime :: Float }
  | Disarmed    ( remTime :: Float }
  | Inert


答:
For interpreted languages: use one that is supported by an "execution platform" (e.g. an application server) OS. That's because you should probably use the same OS for development in a first place. Also you may find yourself in a situation when you need to read or change (not a good idea, but possibility) deployed sources.

For compiled languages: I see no reasons why any choice should be favored, except there is some explicit requirement or if the majority of developers use any particular OS.

Title: Smart fallback for line endings in code files?

Body:
What do you recommend as a default fallback for line endings if the operating system cannot be determined?

Example

Mac OS up to version 9 uses carriage returns (\r) for line endings. Unix-like systems do line endings with line feeds (\n) and Windows uses two characters (\r\n) to mark a line ending.

What's the best fallback which is most compatible for all mentioned systems when writing code files which are exchanged with developers on different platforms?


问:
Does MVC apply only to web
It is almost and instantaneous whenever I talk to developers about Model View Controller (MVC) they say you make a request to a url the server builds a entity (MODEL) and provides you with visual representation of that model.

So does this mean MVC is only for the web or have I been meeting people who are just developers who employ MVC for writing web applications?

Are there usages for MVC on desktop style applications?

I for one am new to paradigm and would like to know of any super-set to MVC

答:
One thing you must know is that there are as many flavours of MVC as there are frameworks that claim to implement MVC.

Most agree on the fact that the Model holds some state and the View renders it.  But the Controller has very different roles.

In Smalltalk, where it was first described, the Model is the core of your application, data and business methods.  The View is a graphical representation of the state of the application (aka Model), and the Controller manages the user input, mouse and keyboard events.  The Controller, for instance, routes keyboard events to the view element that has the focus.

In .jsp pages, the Model is mostly data, the View renders that Model to HTML and the Controller does the routing of the Model to the proper View to render it.

So, to answer your question, while MVC is used both on standalone applications (Java, .Net, Flex) and the web (jsp pages), it is a very different thing.  That means the MVC you know is not used in standalone applications.

Title: Does MVC apply only to web


答:
My 2¢:

Pick any EOL encoding you want, but make sure it plays well with your build system, compilers, interpreters, etc.

Make sure that this is cleanly explained in your wiki page, readme files, etc, intended for contributors.

On the same page explain how to git config core.eol properly, so that contributors have an easy time sending pull requests.

Hopefully after that you'll be able to stop caring about EOLs in source files.


问:
Is it a bad choice to consume the REST API from the back-end too?
Using a REST API for front-end code is a desiderable and quite common practice.

However, I was wondering if using it also for the back-end could be a good choice.

What I mean is leaving the burden of retrieving data from the database all to the API, and then call it from other parts of my back-end (mainly views and controllers) whenever I need to query the database, instead of doing it directly.

One thing I'm really concerned about is sharing some code between front-end and back-end, and using the API as a common source of data would be very handy.

So the question is, are there some reasons which make this a bad idea?

答:
I think the overarching justification out of making data access a RESTful API would be the relationship the data access would have to the rest of the environment.

Think about it, the power of the API is typically the vast amount and variety of "client" implementers that can consume it. That should be no different in your case.

In other words, if you were to have multiple consumers and different invokers of this same data access and/or looking to scale that out, then I think it would make sense.

But conversely, if you have a single consumer and this data access and logic is tailored very specifically so it doesn't scale, I don't know what you would gain out of making the transfer of bits through a RESTful API.


答:
Decoupling components from the database / getting away from direct database connections is a common pattern. Moving access into middleware / a component that front-ends the database can help improve security and modularity, and provide a place to implement data validation and interpretation that would otherwise "fall into" SQL, stored procedures, and client-side database code. Against this you have to weigh the development, runtime, and possibly economic cost of that middleware / data mangement front-end. But at many project scale-points, data front-ends are often considered a good choice.

If you control the backend design and components, using a RESTful API--especially in its common format, e.g. served by HTTP and encoded with JSON--is notably inefficient compared to other alternatives (e.g. direct library linking, Protocol Buffers, Thrift, various kinds of ESB, other RPC mechanisms, ...) that do not go through a serialize-to-text, serve, deserialize-from-text cycle for every API call. REST is also semantically better as an arms-length interaction mechanism, given that some constructs (e.g. multi-step transactions, streaming, large binary objects, raising exceptions, guaranteed delivery, ...) are more simply, cleanly, or directly handled with other forms of interaction.

Some reasons you still might want to use a RESTful backend: simplicity, consistency (every client, local or remote, goes through just one API), and time-to-market (e.g. not needing to learn another API/interaction style). These assume that you are exposing your database, relatively directly, through the RESTful API. If it is strictly for the use of components under your control, REST is probably not the best choice (for either semantic richness or efficiency).

Title: Is it a bad choice to consume the REST API from the back-end too?

Body:
Using a REST API for front-end code is a desiderable and quite common practice.

However, I was wondering if using it also for the back-end could be a good choice.

What I mean is leaving the burden of retrieving data from the database all to the API, and then call it from other parts of my back-end (mainly views and controllers) whenever I need to query the database, instead of doing it directly.

One thing I'm really concerned about is sharing some code between front-end and back-end, and using the API as a common source of data would be very handy.

So the question is, are there some reasons which make this a bad idea?


问:
Including extra headers that I do not really need
I always wondered what are the effects of including not needed headers to the final executable once compiled. In my code some times I may included many different headers that I do not need (or I used to need but now I don't and forgot to remove them). Now before compiling the final executable I always clean up my header files. But I am wondering, is there a problem if I don't?

I am aware that in C# having unused Using in my code only reduces (slightly) the speed of intellisense and the compiler only includes stuff that is really needed. Is the same thing true for C and C++? What about Java and other languages?

答:
If you are not using precompiled headers then each include means that the header is included fully into each compilation unit. That means reading the file and putting it through the same pipeline of the rest of the code and filling the symbol table.

So yeah unused includes will slow down compilation.

Some compilers will have optimizations in place that alleviates most of the parsing work by creating precompiled headers that has just the symbols and templates in a proprietary easy to parse format. However doing the lookup each #include will still take some time.

Java's imports are a bit different, when you import a package (for example import java.util.*) then the compiler will look through the directory/jar specified in the class path and make a map of the public classes in it so ArrayList gets translated to java.util.ArrayList. Similarly for importing a class; it gets looked up and added to the translation table. Doing a static import requires looking in the class file and parsing the public declarations in it.


答:
Importing in Java, C# and the like is fundamentally different from including in C and C++:

The former will add the named modules to those considered for symbol resolution, the latter inserts the named headers content literally into the translation unit.

Which means a header can contain anything the source-file can, including translation-unit-local objects (They might have a constructor and destructor in C++), functions, structs (and for C++ classes).

Which is not quite as bad as it sounds for C, as headers tend to mostly contain forward-declarations, struct definitions and preprocessor-macros.

In C++ on the other hand, templates (which are far more powerful than puny Java or C# generics) generally must be implemented in headers, which makes them grow to considerable size and complexity (often outstripping by orders of magnitude the source-file of the translation-unit).

The C++ committee is working on a module-system to take care of that, but at the earliest it will be there in C++17 (and don't hold your breath yet).

So, for the languages with module-system (Java, C#) you will only have a slight slowdown for analysis and compilation.

For C, you will probably only have a slightly higher slowdown, due to literal inclusion of the source, though at least they tend not to be too big and complex.

For C++, you will have a moderate to severe slowdown of compilation and analysis, due to heavy use of templates and inline-functions.

In both C and C++ headers can in theory contain TU-local objects, which would result in some runtime overhead.

While I know that such is used by C++ for <iostream> (look for ios_base::Init in the standard) to initialize the C++ streams early enough, I don't know of any use in C.

Title: Including extra headers that I do not really need

Body:
I always wondered what are the effects of including not needed headers to the final executable once compiled. In my code some times I may included many different headers that I do not need (or I used to need but now I don't and forgot to remove them). Now before compiling the final executable I always clean up my header files. But I am wondering, is there a problem if I don't?

I am aware that in C# having unused Using in my code only reduces (slightly) the speed of intellisense and the compiler only includes stuff that is really needed. Is the same thing true for C and C++? What about Java and other languages?


问:
The source is the documentation - part 1
Searching the specification for the btrfs file system i stumbled once more over the catchphrase: "The code is the documentation". This implies that changing the code changes the specification.

Does this approach make sense while working on a file system that will be used from various drivers or applications?

I can understand that a smal group can split the job and everyone works on her own task. But how should this work with a larger group, spread over several places?

(btrfs spec would still be welcome)

答:
I  can understand that a small group can split the job and everyone works on her own task. But how should this work with a larger group, spread over several places?

Well if you think about it, it works the same way that all distributed development projects work.  The developers uses tools (e.g. distributed version control) and procedures that are tried and tested for this kind of situation.

And the evidence is that this approach really does work ... if done properly.

One thing that works in the favour of the "the code is the spec" approach for a file system, is that a Linux file system only requires a single master implementation.  From the developers perspective, there is no need for multiple implementations of (say) BTRFS, and certainly no need for independent (e.g. clean-room) re-implementations.  If you look at it from their point of view, there is no value to them in writing a spec, setting up a committee to manage changes to the spec, and constraining themselves to conforming to the spec.

jmoreno comments:

For something like a file system, I would expect a reference implementation and/or a test suite, which would be the documentation.

You could say that the master implementation is the reference implementation, and the master test suite is the reference test suite.  The only issue is that the test suite will have been designed as a functionality test suite for the master (reference) implementation rather than as a compliance test suite for all possible implementations of a (hypothetical) spec.


答:
Since you are hiring fresher in India, my suggestion would be like following.

Resume :
This will tell you their confident and clarity of their knowledge will clearly. Many people follows the template resume from Naukri or some of the websites and will put the polished words, but not about their skills. This will surely indicate that they are not capable for doing independently.

See their academic score from resume. If it is above 65% to 70% consistently across the all level, you can have confident that they can work consistently.

See Clarity of resume that how much of their own stuff they have put. Even if there is no their own stuff, it is really good than they took from the templates. Because, you need a true people than people who are making up as they are good.

Make comfortable them in the interview hall first. This is very important for fresher since they will get easily tensed and they will not be able to present by themselves because of nervousness even they are good.

Talk with them politely and ask questions related to their comfortable technical language/topic.

You should keep one important thing in your mind that our education system. It is not good in India in-terms of practical learning since here they concentrate only in theoritical stuffs rather than practical. It makes complex to the fresher as well as interviewer. So, you can give low priority to their interview score in technical knowledge than their personal skills and consistent academic score.

Ofcourse, their maths(including logical) skill should be good. you can ask them about their mark in all level and this will also give you a clue whether they are a good problem solver. Or else, you can ask some simple logical & puzzles to determine their capability additionally.

Body:
I really want to ask this questions to my fellow developers here in Programmers.SE because i am hiring freshers for my company.. Even though i know some basic questions that can be asked to a fresher during interview and i want to know,

What are the skills you look for when hiring a fresher/newbie for developement?


问:
Why was C# made with "new" and "virtual+override" keywords unlike Java?
In Java there are no virtual, new, override keywords for method definition. So the working of a method is easy to understand. Cause if DerivedClass extends BaseClass and has a method with same name and same signature of BaseClass then the overriding will take place at run-time polymorphism (provided the method is not static).

BaseClass bcdc = new DerivedClass();
bcdc.doSomething() // will invoke DerivedClass's doSomething method.
```

<hr>

<p>Now come to C# there can be so much confusion and hard to understand how the <code>new</code> or <code>virtual+derive</code> or new + virtual override is working. </p>

<p>I'm not able to understand why in the world I'm going to add a method in my <code>DerivedClass</code> with same name and same signature as <code>BaseClass</code> and define a new behaviour but at the run-time polymorphism, the <code>BaseClass</code> method will be invoked! (which is not overriding but logically it should be). </p>

<p>In case of <code>virtual + override</code> though the logical implementation is correct, but the programmer has to think which method he should give permission to user to override at the time of coding. Which has some <em>pro-con</em> (let's not go there now).</p>

<p>So why in C# there are so much space for <em>un</em>-logical reasoning and confusion. So may I reframe my question as in which real world context should I think of use <code>virtual + override</code> instead of <code>new</code> and also use of <code>new</code> instead of <code>virtual + override</code>?</p>

<hr>

<p>After some very good answers especially from Omar, I get that C# designers gave stress more about programmers should think before they make a method, which is good and handles some rookie mistakes from Java. </p>

<p>Now I've a question in mind. As in Java if I had a code like</p>

<pre class="lang-java prettyprint-override"><code>Vehicle vehicle = new Car();
vehicle.accelerate();
</code>```

and later I make new class SpaceShip derived from Vehicle. Then I want to change all car to a SpaceShip object I just have to change single line of code

```<code>Vehicle vehicle = new SpaceShip();
vehicle.accelerate();
</code>```

This will not break any of my logic at any point of code.

But in case of C# if SpaceShip does not override the Vehicle class' accelerate and use new then the logic of my code will be broken. Isn't that a disadvantage?

答:
Defaulting to non-virtual assumes that the base class developer is perfect. In my experience developers are not perfect. If the developer of a base class cannot imagine a use case where a method could be overridden or forgets to add virtual then I cannot take advantage of polymorphism when extending the base class without modifying the base class. In the real world modifying the base class is often not an option.

In C# the base class developer does not trust the subclass developer. In Java the subclass developer does not trust the base class developer. The subclass developer is responsible for the subclass and should (imho) be given the power to extend the base class as they see fit (barring explicit denial, and in java they can even get this wrong).

It's a fundamental property of the language definition. It isn't right or wrong, it is what it is and cannot change.


问:
What's wrong with statically linking the STL into multiple shared libraries?
Here is the scenario:

libA.so and libB.so both statically link to the same STL.

libA.so has a public API that returns a std::string.

libB.so calls this function and receives a copy of the string.

When libB.so's copy of the string goes out of scope the string's destructor is called.

The application seg faults attempting to free the copied string.

I've read elsewhere that statically linking like this is bad but I'd like to better understand why it's bad.  Can anyone explain why the above sequence would crash?

答:
The STL is so-called "state-full" (as opposite to being "state-less") meaning that it has some static stuff inside. When you link STL statically to both libA.so and libB.so you get two instances of STL library in memory at run-time (with two copies of static stuff).
Each of those two copies manages allocated resources independently and resource allocated in one instance of library cannot be freed in another </p>


答:
Let's think about this very carefully. libA.so is statically linked with the STL. However, the STL does not exist in isolation, it requires the C runtime (CRT). They both reside in the libstdc++.a static library. This means that libA.so and libB.so have separate CRT data structures. In particular, the heap used by libA.so is different from the heap used by libB.so. Allocating a string from libA's runtime heap and attempting to free from libB's runtime will simply not work because libB's runtime has no records of allocating the string. The only way to correctly destruct the string is by calling the destructor within libA.so.

One might ask: but libB.so receives a copy of the string, right? Yes that's right but who has allocated this copy? It has been allocated using the copy constructor within the context of the libA's runtime.

That said, you can still use the string from libB.so. You just cannot destruct it from there.

You can also let libB receive a pointer to the string and then creating a copy of it within the context of the libB's runtime. That copy can be destructed by libB.

And that's why static linking is sometimes bad.

Title: What's wrong with statically linking the STL into multiple shared libraries?

Body:
Here is the scenario:

libA.so and libB.so both statically link to the same STL.

libA.so has a public API that returns a std::string.

libB.so calls this function and receives a copy of the string.

When libB.so's copy of the string goes out of scope the string's destructor is called.

The application seg faults attempting to free the copied string.

I've read elsewhere that statically linking like this is bad but I'd like to better understand why it's bad.  Can anyone explain why the above sequence would crash?


答: One more downside in C/++ to including an unneeded header in a source file:  if precompiled headers are not used, then changing that unneeded header file forces recompilation of that source file.</p>


问:
What are the advantages/disadvantages of creating a new set of tables for each user?
I'm working/playing on an app where individual users' data will be completely independent from each other. Of course, there will be common tables for other parts of the app (e.g. "users"), but for the rest of the tables, would it be wise to create a new set of tables for each user?

e.g.

```<code>List of tables:
users
user1_transactions, user1_items, user1_tags
user2_transactions, user2_items, user2_tags
</code>```

for a total of 7 tables for the 2 users.

Would I have trouble with migrations with this setup (assuming the condition that user data will always be independent)?

I don't have much experience with relational design, so I guess this is a "I don't know what I don't know" situation. Is this a bad idea?

答:
It's a terrible idea to be honest and there are a handful of immediate issues with that I can think of off the top of my head:-

modifying the table structure becomes very difficult because of the number of tables you need to modify.

you have to grant rights the app to change the table structure which is opposite to the principle of 'least privilege'.

you're mixing your data structure with your actual data which goes against the separation of concerns and mixes the design with the data.

migration shouldn't be a major concern although you do need to make sure that table names are unique.

That's all before we get into any issues of performance or limits on the number of tables or consider the impacts of how Indexing, and Views which will be useless across these multiple tables.

You're better off sticking with:

```<code>Users
Transactions
Items
Tags
</code>```

You might find some useful information about designing your tables properly in Is it necessary to create a database with as few tables as possible

Body:
It's a terrible idea to be honest and there are a handful of immediate issues with that I can think of off the top of my head:-

modifying the table structure becomes very difficult because of the number of tables you need to modify.

you have to grant rights the app to change the table structure which is opposite to the principle of 'least privilege'.

you're mixing your data structure with your actual data which goes against the separation of concerns and mixes the design with the data.

migration shouldn't be a major concern although you do need to make sure that table names are unique.

That's all before we get into any issues of performance or limits on the number of tables or consider the impacts of how Indexing, and Views which will be useless across these multiple tables.

You're better off sticking with:

Users
Transactions
Items
Tags

You might find some useful information about designing your tables properly in Is it necessary to create a database with as few tables as possible


问:
Number of sequences when no adjacent items can be the same
I came across this one problem,

There is a particular sequence only uses the numbers 1, 2, 3, 4 and no two adjacent numbers are the same.
  Write a program that given n1 1s, n2 2s, n3 3s, n4 4s will output the number of such sequences using all these numbers.
  Output your answer modulo 1000000007 (10^9 + 7).

I can't figure out the solution of this. Will this be done with DP or some kind of DFS with backtracking?

答:
If I'm correct, the graph traversal solution is pretty straightforward: you may traverse the graph with recursive function memorizing only current "left" symbols and last used one.

let there be a function f of input (key-value pairs, where keys are 1..4; values are n1..n4) and p - last used number, and p is initially undefined

in a loop, if input[i] > 0 and i != p, where i is a key

add 1 to result, because you found another solution, 1 symbol longer

set inputUpd := input (copy for recursive call)

decrement inputUpd[i], because we've just used symbol i and there is one such symbol less left

set p := i, because we've just used i

add the value of f(inputUpd, p) (recursive call with "smaller" input and last used symbol) to result

I couldn't help myself, so here is the code in JS. Skip it if you want to figure out the solution yourself.

```<code>function f(input, prev) {
  var acc = 0;
  for (i in input) {
    if (i != prev && input[i] > 0) {
      var inputUpd = {};
      for (j in input) {
        inputUpd[j] = (j == i) ? (input[j] - 1) : input[j];
      }
      acc += 1 + f(inputUpd, i);
    }
  }
  return acc;
}

f({'1': 1, '2': 1}) // -> 4: [1], [2], [1,2], [2,1]
f({'1': 1, '2': 2}) // -> 5: [1], [2], [1,2], [2,1], [2,1,2]
f({'1': 1, '2': 3}) // -> 5: same as before, but single `2` is leftover
f({'1': 1, '2': 1, '3': 2, '4': 2}) // -> 288
</code>```

Body:
If I'm correct, the graph traversal solution is pretty straightforward: you may traverse the graph with recursive function memorizing only current "left" symbols and last used one.

let there be a function f of input (key-value pairs, where keys are 1..4; values are n1..n4) and p - last used number, and p is initially undefined

in a loop, if input[i] > 0 and i != p, where i is a key

add 1 to result, because you found another solution, 1 symbol longer

set inputUpd := input (copy for recursive call)

decrement inputUpd[i], because we've just used symbol i and there is one such symbol less left

set p := i, because we've just used i

add the value of f(inputUpd, p) (recursive call with "smaller" input and last used symbol) to result

I couldn't help myself, so here is the code in JS. Skip it if you want to figure out the solution yourself.

function f(input, prev) {
  var acc = 0;
  for (i in input) {
    if (i != prev && input[i] > 0) {
      var inputUpd = {};
      for (j in input) {
        inputUpd[j] = (j == i) ? (input[j] - 1) : input[j];
      }
      acc += 1 + f(inputUpd, i);
    }
  }
  return acc;
}

f({'1': 1, '2': 1}) // -> 4: [1], [2], [1,2], [2,1]
f({'1': 1, '2': 2}) // -> 5: [1], [2], [1,2], [2,1], [2,1,2]
f({'1': 1, '2': 3}) // -> 5: same as before, but single `2` is leftover
f({'1': 1, '2': 1, '3': 2, '4': 2}) // -> 288


答:
Your solution is not relational and has a lot of disadvantages, to name a few:

nearly impossible to do some queries involving data for multiple users

no constraints can be used, therefore no consistency of your data

hard to deal with privileges

hard to migrate (if user ID is somehow changes, you're done)

There probably should be those tables:

users, having id field

transactions, items, and tags tables, all having user_id field which point to users.id - this is called "one-to-many relation", since each user can have multiple transactions, items and tags.

If, for example, tags can be shared between users, you should instead have tags table just have id, and also a table users_tags with two fields: user_id and tag_id, which connects users and tags with many-to-many relation.

You have to learn at least basics of database normalization and RDBMS in general before even attempting to design a schema. Database design is moderately difficult (depending on a task) topic, not something you can start with in couple of days.

Title: What are the advantages/disadvantages of creating a new set of tables for each user?

Body:
I'm working/playing on an app where individual users' data will be completely independent from each other. Of course, there will be common tables for other parts of the app (e.g. "users"), but for the rest of the tables, would it be wise to create a new set of tables for each user?

e.g.

```<code>List of tables:
users
user1_transactions, user1_items, user1_tags
user2_transactions, user2_items, user2_tags
</code>```

for a total of 7 tables for the 2 users.

Would I have trouble with migrations with this setup (assuming the condition that user data will always be independent)?

I don't have much experience with relational design, so I guess this is a "I don't know what I don't know" situation. Is this a bad idea?


答:
I've recently done a fair bit of hiring. The first thing I'm looking for is basic coding skills. We get our agent to make them sit technical test which asks them to write some basic algorithms (and also some SQL).

If they do well enough in that, we'll get them in for an interview. If they have good communication skills, and don't seem too full of themselves, it's a likely hire.

Title: What are the skills you look for when hiring a fresher/newbie for developement?


问:
How to manage coupling in model classes
I'm doing a class diagram for a game project, but I'm stuck on a coupling problem.

Context

The projet is a turn-based game. Two users are playing. They've got units on a map. They play until 1 player has all his units dead or if a predefined number of turns are reached.
At each round, each player will review his units one by one:

he can move an unit until the unit hasn't got any movement point left

he can skip the unit's turn

Modeling

Classes irrelevant to the questions have been cut

The Game class holds all the relevant objects : the players, the units, the current turn (which player(s) have already played, who's next, ...). The Turn object holds a PlayerTurn object, which keeps tracks of which units have already been played, which units are left to play, ...

Problem

-> Let's suppose we're creating the GetNextPlayableUnit method (in class PlayerTurn).

We'll have to iterate through the current player's units and find one that is not in the "PlayedUnits" list. Therefore, we'll have to call Game.Units.GetUnits with the parameter Game.Turn.CurrentPlayer (Game refers to the current Game's instance).

-> Let's suppose we're creating the MoveTo method (in class Unit).

If the Unit hasn't got any movement point left, we'll have to call Game.Turn.PlayerTurn.Finish which will either select the next playable unit or finish the current player's turn if he already played all of his units this turn.

-> ... There are a lot of other scenarios where we'll need to access other classes' method. E.g., a "Kill" method on Unit will have to check if the current player has still got at least 1 unit alive, and it will have to call a Finish method on Game otherwise.

Question

I think the coupling can't be avoided (correct me if I'm wrong though!). I've thought about two possible ways of dealing with coupling:

Solution 1

When constructing instances of these classes, I could pass the current Game's instance. After all, it makes sense: Unit instances, Turn instances, ... all belong to a game.
Then, I could implement the methods GetNextPlayableUnit, MoveTo, Killed, ... easily by using this instance. Somehow, I don't feel comfortable sharing the current game's instance between all the model classes, even though I read here and there that it was the principle of dependency injection.

Solution 2

Analyse the method dependencies: e.g., Kill method depends on Game.Units.Unit.Player (to retrieve the Player owning the Unit), on Game.Units.GetUnits (to find all other Units owned by the player), on Game.End to end the game if unit count of the player has reached 0.

Find the dependencies common root: in the example above, the common root between Game.Units.Unit, Game.Units and Game is Game. In another example, if we had the dependencies Game.Units.Unit & Game.Units.SomethingElse, the common root would be Game.Units.

Implement the method in this common root class. We're guaranteed not to need to access parent classes (in the association hierarchy).

Risks:

lots of methods will have the Game class for common root => lots of methods in Game class => lots of code in Game class.

methods won't belong to their rightful classes. Consider the method "KillUnit": you'd expect to find it in the Unit class directly, not in the Game class. Same goes for "MoveTo", "Finish", ...

Is there any other solution you can think of? What would be the best approach in this particular case?

答:
You ask about other solutions. These might be reflections on your process of finding solutions:

This is your first version of the diagram and you do not want to throw it away and restart. It  makes it more likely that you mix old, maybe irrelevant thoughts with new thoughts.

While you model you think about implementing it. That mixes how you think the model should be and how the programming language wants it to look like. Modeling is not implementing. You should end up with more methods and hopefully more classes in your implementation than your model.

I think the Units class is one way of implementing the desired behavior. It can be let out at your level of granularity. For example, the Player class does not point at a String-subclass PlayerName. Keep one level of granularity in your diagrams.

Starting with a class diagram might not be the choice. An object diagram is more specific. Class diagrams are more general. So I think one can get lost in generalizations that do not need to make sense.

You have different scenarios, play-throughs. You can make several object diagrams from them and generalize from there. No need to put everything in one diagram at once.

To your concern: behavior can be found in several methods Unit.Die() Playfield.RemoveUnit(), Player.KillUnit() at the same time. That is OK. But you want to avoid copy and pasting the code into every method.

About coupling. I think you do/can/must/want not avoid coupling. Some objects should interact. A bad case is when all objects always interact with all other objects in every method. That is too much coupling with no separation of concerns.

And maybe an outdated opinion: OOP is about objects and their interactions, not about classes, not about inheritance.

Title: How to manage coupling in model classes