问:
Unknown design pattern
I am currently trying to refactor some code and one of the problems I came across was the constructors had far too many parameters (15 in fact) and was being initialised by another object which had the same amount of properties.

I am meant to be reducing the amount of classes we have so creating a set of classes which represented the different parts of the parameters seemed silly so I began looking and the best answer I came across was from  this question on stackoverflow.

```<code>public class DoSomeActionParameters
{
    readonly string _a;
    readonly int _b;

    public string A { get { return _a; } }
    public int B{ get { return _b; } }

    DoSomeActionParameters(Initializer data)
    {
        _a = data.A;
        _b = data.B;
    }

    public class Initializer
    {
        public Initializer()
        {
            A = "(unknown)";
            B = 88;
        }

        public string A { get; set; }
        public int B { get; set; }
    }

    public static DoSomeActionParameters Create(Action<Initializer> assign)
    {
        var i = new Initializer();
        assign(i)

        return new DoSomeActionParameters(i);
    }
}
</code>```

which can be called like so using a lambda

```<code>DoSomeAction(
    DoSomeActionParameters.Create(
        i => {
            i.A = "Hello";
        })
    );
</code>```

I really liked this method even though it doesn't solve directly the problem of actually initialising the class, it does make it mean that I can have one constructor instead of 3. Also it doesn't require my class to know about objects it doesn't care about.

My problem is however, I do not know what this pattern is called so I can't do any further research on it to find out if it is still valid, is superseded by
another pattern or whether it has sever performance issues. From my research the closest pattern I could find is the builder pattern but it seems to be more of an extension on that.

As a bonus point, it would be great if you could give me a hand with how to make certain parameters mandatory as we have about 10 parameters from the database and 5 more which are just flags which we don't really need to know about.

答:
I am creating my own answer (after a discussion on meta) because I believe that the correct answer is in fact a combination of everything so far.

Firstly as DavidArno put, the pattern that I have asked about is more of an anti-pattern because it is just hiding the problem somewhere else. However I believe the suggestion of using the builder pattern from the answer by Carl Manaster does solve the issue that I have because I cannot break down the list of parameters without over-engineering the Single Responsibility Principle.

The problem I had with the builder pattern was that there was no way to make it easy for a developer using it to know about the mandatory fields which will mean there will be lots of trial and error which will lead to copy and pasting the initialisation everywhere which will lead to more mistakes. Fuhrmanator however linked to the following blog which demonstrates how to have mandatory fields with the builder pattern (after looking elsewhere I believe this is called a Step Builder).

Essentially the principle of the Step Builder is to guide a developer through the initialisation of all the mandatory fields. Your builder implements various interfaces which act as steps to create the object. They each have a method which have a return type of the next step. This aids intellisense more than the standard builder patter as well because it cuts down the amount of methods you can call. See the following example from the blog.

```<code>public class Address {
private String protocol;
private String url;
private int port;
private String path;
private String description;

// only builder should be able to create an instance
private Address(Builder builder) {
    this.protocol = builder.protocol;
    this.url = builder.url;
    this.port = builder.port;
    this.path = builder.path;
    this.description = builder.description;
}

public static Url builder() {
    return new Builder();
}

public static class Builder implements Url, Port, Build{
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    /** Mandatory, must be followed by {@link Port#port(int)}  */
    public Port url(String url) {
        this.url = url;
        return this;
    }

    /** Mandatory, must be followed by methods in {@link Build}  */
    public Build port(int port) {
        this.port = port;
        return this;
    }

    /** Non-mandatory, must be followed by methods in {@link Build}  */
    public Build protocol(String protocol) {
        this.protocol = protocol;
        return this;
    }

    /** Non-mandatory, must be followed by methods in {@link Build}  */
    public Build path(String path) {
        this.path = path;
        return this;
    }

    /** Non-mandatory, must be followed by methods in {@link Build}  */
    public Build description(String description) {
        this.description = description;
        return this;
    }

    /** Creates an instance of {@link Address} */
    public Address build() {
        return new Address(this);
    }
}

interface Url {
    public Port url(String url);
}

interface Port {
    public Build port(int port);
}

interface Build {
    public Build protocol(String protocol);
    public Build path(String path);
    public Build description(String description);
    public Address build();
}
</code>```

You have the collection of Mandatory parameters which each return the next statement but also what I think is great about this is that you can have optional parameters as well by making the methods return type the build interface.

This solves my problem because I had mandatory parameters mixed in with optional ones which made expanding it difficult as there was lots of copy and pasting and potential problems. With the step builder I can control how a developer creates my object so that I have facts to use in the future, and I allow them the flexibility of creating the object in as many ways as they possibly need to.

Also it makes it very readable!

Title: Unknown design pattern

Body:
I am creating my own answer (after a discussion on meta) because I believe that the correct answer is in fact a combination of everything so far.

Firstly as DavidArno put, the pattern that I have asked about is more of an anti-pattern because it is just hiding the problem somewhere else. However I believe the suggestion of using the builder pattern from the answer by Carl Manaster does solve the issue that I have because I cannot break down the list of parameters without over-engineering the Single Responsibility Principle.

The problem I had with the builder pattern was that there was no way to make it easy for a developer using it to know about the mandatory fields which will mean there will be lots of trial and error which will lead to copy and pasting the initialisation everywhere which will lead to more mistakes. Fuhrmanator however linked to the following blog which demonstrates how to have mandatory fields with the builder pattern (after looking elsewhere I believe this is called a Step Builder).

Essentially the principle of the Step Builder is to guide a developer through the initialisation of all the mandatory fields. Your builder implements various interfaces which act as steps to create the object. They each have a method which have a return type of the next step. This aids intellisense more than the standard builder patter as well because it cuts down the amount of methods you can call. See the following example from the blog.

public class Address {
private String protocol;
private String url;
private int port;
private String path;
private String description;

// only builder should be able to create an instance
private Address(Builder builder) {
    this.protocol = builder.protocol;
    this.url = builder.url;
    this.port = builder.port;
    this.path = builder.path;
    this.description = builder.description;
}

public static Url builder() {
    return new Builder();
}

public static class Builder implements Url, Port, Build{
    private String protocol;
    private String url;
    private int port;
    private String path;
    private String description;

    /** Mandatory, must be followed by {@link Port#port(int)}  */
    public Port url(String url) {
        this.url = url;
        return this;
    }

    /** Mandatory, must be followed by methods in {@link Build}  */
    public Build port(int port) {
        this.port = port;
        return this;
    }

    /** Non-mandatory, must be followed by methods in {@link Build}  */
    public Build protocol(String protocol) {
        this.protocol = protocol;
        return this;
    }

    /** Non-mandatory, must be followed by methods in {@link Build}  */
    public Build path(String path) {
        this.path = path;
        return this;
    }

    /** Non-mandatory, must be followed by methods in {@link Build}  */
    public Build description(String description) {
        this.description = description;
        return this;
    }

    /** Creates an instance of {@link Address} */
    public Address build() {
        return new Address(this);
    }
}

interface Url {
    public Port url(String url);
}

interface Port {
    public Build port(int port);
}

interface Build {
    public Build protocol(String protocol);
    public Build path(String path);
    public Build description(String description);
    public Address build();
}

You have the collection of Mandatory parameters which each return the next statement but also what I think is great about this is that you can have optional parameters as well by making the methods return type the build interface.

This solves my problem because I had mandatory parameters mixed in with optional ones which made expanding it difficult as there was lots of copy and pasting and potential problems. With the step builder I can control how a developer creates my object so that I have facts to use in the future, and I allow them the flexibility of creating the object in as many ways as they possibly need to.

Also it makes it very readable!


问:
Is writing code chronologically the best way for readability?
So I've been writing a lot of JavaScript lately. Despite what many people say I think JavaScript can be a simple and beautiful language.

What I've pondered of late is how to structure the code so it is best readable to the human eye.

Sometimes there are cases like this:

```<code>mainFunction = function(){
  var init = function(){
    // do some initialization
    doSomeThing();
    doAnotherThing();
    window.addEventListener("scroll", someCallback);
  }
  var someCallback = function() {}
  var doSomeThing = function() {
    // code
  }

  var doAnotherThing = function() {
    // code
  }

  init();
}
</code>```

You first have to define all functions before you can initialize some thing and finally do the stuff you wanted to do.

Now when I'm reading code, I always try to read it in a chronological order first, that's just how my brain works. But with JavaScript, the longer the code gets, the more complex I find to see where the start point is.

So I guess my questions are:

Are most people reading code chronologically? Is chronological the best way for readability?

How to achieve this in JavaScript? (What are some languages that do it better)

What are some common JavaScript code writing philosophies out there?

答:
If putting the functions chronologically improves the readability of the code, it means that you are using functions wrong. The primary purpose of dividing the code to function is to reduce the amount of context you need to hold in your mind at any given time.

(functions have other usages when you use recursion or higher-order functions, but that's clearly not the case in your example(maybe except someCallback))

"The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague."

  Dijkstra (1972) The Humble Programmer (EWD340).

You break the big code into smaller functions so you can look at each function on it's own, and only have to think of what one function does at any given moment. Even with functions that call other functions(like the mainFunction) you don't think about what each of these functions does, instead abstracting them to atomic commands. This means you don't have to look at the entire flow of the program as a whole - so it doesn't matter if the functions are ordered according to that flow.

ContentLicense: CC BY-SA 3.0


问:
Clean Abstract Syntax Tree
I'm writing a toy compiler for fun.

Basically, my problem is that I don't want to clutter the AST with stuff like debug information (symbol tokens, locations of tokens, etc) as well as data that the semantic analyzer computes.

For example, the semantic analyzer does some type inference and the result type is stored back into the Node type. It looks something like this:

```<code>/// A variable declaration in my language looks like this:
/// var x = 10
struct VarDec: Statement {
    var varKeyword: Keyword
    var varName: Id
    var assignment: Symbol
    var initializer: Expr
    var type: Optional<Type>
}
</code>```

The main problem here is that now the node type has a state, type inference has either been done or not. This makes it hard to reason about. The other thing is that the whole AST gets cluttered with those tokens that are only really needed for error messages.

It has been suggested that I could create another representation of the AST just for semantic analysis that links back to the AST but that seems like a lot of work and redundant code...

Does anybody have an idea how I can clean up this code without having to create multiple trees?

答:
The main problem here is that now the node type has a state, type inference has either been done or not. This makes it hard to reason about.

Only to a person whose brain has been damaged by an overdose of Strict Immutability flavored Kool Aid.  The reasoning is actually quite simple: if the value is null, one can clearly deduce that type inference has not run yet.  If the value is not null, one can just as clearly deduce that type inference has run already.  Where's the hard part?

Also, unless you're running a strict one-pass compiler, your entire AST is going to be one huge mass of mutable state, with each pass refining and simplifying things until you're ready for code generation.

The other thing is that the whole AST gets cluttered with those tokens that are only really needed for error messages.

Error messages are very important for a compiler.  Aside from actually compiling working code, producing useful feedback about what the code definitely (errors) or probably (warnings) did wrong is the single most important thing a compiler can do, and if you give useless or misleading error messages, your users will hate you for it.

If you want to keep the interface of the node classes clean, though, one thing you could do is create a separate class for all the token data.  Call it LexicalInfo and have it store information like the filename, starting point (line and column) and ending point (line and column, and the lines might be different if you support multiline strings) of each token.

Title: Clean Abstract Syntax Tree


问:
Declaring 'chained' interface inheritance

I assume this is largely language-agnostic, but I'm working in C# if it's not

Let's say interface I3 inherits from I2, which in turn inherits from I1. I could write this:

```<code>interface I1 { ... }
interface I2 : I1 { ... }
interface I3 : I2 { ... }
</code>```

Or alternatively this:

```<code>interface I1 { ... }
interface I2 : I1 { ... }
interface I3 : I1, I2 { ... }
</code>```

The I1 in interface I3 is redundant - anything that implements I3 will still require anything declared in I2, which includes anything in I1.

To my mind the latter is more readable - I can see at a glance all the 'base' interfaces without having to dig down the inheritance tree - but I'm not sure if it's considered good practice. Is it? Are there any hidden traps here?

答:
Having deep hierarchies of interfaces is a bit of an antipattern to me. It smells of overengineering.

The whole point of having interfaces is that they allow for horizontal code reuse rather than vertical (by inheritance).

I don't know the context, maybe there's no way around it in your case. Perhaps it is somehow required by the framework, architecture, or otherwise by the nature of your project - eg. highly abstract code such as standard libraries.

Note that this sort of redundancy can be found in .NET sources, for instance:

```<code>public interface IList : ICollection, IEnumerable
</code>```

Even though ICollection supports IEnumerable already. Same thing with standard Java collections.

What's the cost of it? Redundancy being redundancy, if one day you decide to remove the dependency I2 has on I1, you may have to do this in multiple places, or end up with an inconsistent codebase.

The design does no longer follow the "single source of truth" principle, since the dependency of I2 on I1 is reiterated everywhere instead of stated just once.

Body:
Having deep hierarchies of interfaces is a bit of an antipattern to me. It smells of overengineering.

The whole point of having interfaces is that they allow for horizontal code reuse rather than vertical (by inheritance).

I don't know the context, maybe there's no way around it in your case. Perhaps it is somehow required by the framework, architecture, or otherwise by the nature of your project - eg. highly abstract code such as standard libraries.

Note that this sort of redundancy can be found in .NET sources, for instance:

public interface IList : ICollection, IEnumerable

Even though ICollection supports IEnumerable already. Same thing with standard Java collections.

What's the cost of it? Redundancy being redundancy, if one day you decide to remove the dependency I2 has on I1, you may have to do this in multiple places, or end up with an inconsistent codebase.

The design does no longer follow the "single source of truth" principle, since the dependency of I2 on I1 is reiterated everywhere instead of stated just once.


问:
Calculate different prices for different user types
I'm working on a website that, among other things, sells courses. Each course is segmented in units, to which users can subscribe but is not a requirement that they subscribe to all of them. Now the client asked me to be able to configure different prices to course's units based on the user type and membership status (they can pay an annual fee to become members and get discounts). Also, subscribing to all units of the same course gives the user a discount. An example for a course would be like this:

Website users with no membership:

Unit 1: $500

Unit 2: $500

Unit 3: $500

All Units: $1200

Website users with membership but with debt on the annual fee:

Unit 1: $450

Unit 2: $450

Unit 3: $450

All Units: $1100

Website users with membership (no debt):

Unit 1: $400

Unit 2: $400

Unit 3: $400

All Units: $900

Whether an user is member or not is easy because there is a column that defines that. But then there is another table to log the user's payments, which should be used to get the last payment and deduce if the user has a debt. Based on that combination, the correct prices should be presented to the user.

The client needs to download then a list of users who subscribed to a specific course/unit, so I can't just have three "Unit 1" rows on the database for each price because they should be treated as the same unit.

Regarding the "All Units" price, I can initially keep it simple and add it as another unit to avoid wasting time programming that because it's more important to solve the logic of the different prices.

My question is: How should I structure the database, and what is the best way (logic) to deduce which price is shown to the user?.

Initially the request was different prices for members/not-members which is easy because I can filter by the is_member column of the users table, but then they add to the request the debt status for each user, making it more complex.

I'll be using PHP & MySQL, but the question is more about the logic than the code.

One idea that came to my mind was to get from the database the user info + debt status in one query, and all the course's units and prices in another query and then use PHP to check which values should be used, but how can I implement that logic if the rules can be different for each course (another course will have a discount for users which have been members for 2+ years). Should I manually program Classes for each course (all implementing the same Interface) that do the logic and define in the courses table which Class should be used? I think it's not the best way but I can't think of another option to change the PHP logic according to the selected course.

答:
Definitely implement the rules in PHP. SQL is for data, not business logic or other behavior. There is a third option, implement rules as expressions stored in the DB and have PHP evaluate them, but that way madness lies. The rules should be pre-defined, not defined when configuring a course's pricing in a domain-specific language.

Early on, you should decide whether to model the different price options as discounts (an amount is subtracted from the course's base price) or differential pricing (price is associated with each rule; a course has no base price). You can also combine the two by supporting relative pricings (e.g. "75%", "-$50") in addition to absolute pricings (e.g. "$300"), in which case courses have base prices, but they're not referenced outside of pricings. Which you pick shouldn't have a major impact overall, but will have small affects and will inform the design.

As for implementation, you could use something like the strategy pattern, with pricings like strategies and courses like contexts. The primary Pricing method (e.g. __invoke()) would take a course & a user and return an amount or, if the user isn't eligible for the pricing, NULL. Alternatively, have two primary methods: one to tell whether the user is eligible for the pricing, and another to return the amount (less strategy-like, but might make more sense for your overall design). In addition to the special pricings requested by the client, you'd have an Always pricing that represents no discount and is always applicable. A Course has a collection of pricings (which is one thing that makes this not follow the strategy pattern). Determining whether a user is in good standing (i.e. doesn't owe anything on the annual fee) would be handled by a User method (or by a method of whatever class is responsible for managing a user's transactions, e.g. Account: $user->account->inGoodStanding()).

To determine the final price, you'll need to determine a strategy precedence. One option is to define in code, implicitly or explicitly, a total order for pricings (Always would be the minimum). Another would be to rely on a sequence type for Course->pricings, and apply the pricings in this sequence. To ensure every course has a final price, end the sequence with an Always. With Pricing::__invoke() returning NULL, you can think of this as a coalescing operation. The latter precedence is easier to implement and more flexible, but potentially allows for errors (courses without an applied pricing, or with unreachable pricings). You can prevent some (all?) precedence errors by having & using a course's base price as a fallback instead of an Always sentinal.

Note that some pricings could be based on others (e.g. is-a-member could be implemented as has-been-a-member-for(0)). Whether & when to do this depends on other design details. Be careful to follow proper OO principles if you do this. For example, use inheritance only if overridden properties are effectively immutable so as not to violate LSP. If not, you could end up with an is-a-member that has a non-zero period.

When it comes to the DB design, you can leave it to an ORM. Since data outlasts applications, you want to use an ORM that properly accounts for object-relational impedance mismatch (or procedural-relational impedance mismatch, as strategies can be viewed as procedures encapsulated by objects), which is the biggest problem with this approach. Specifically, different strategies have different arities, and dealing with a variable number of parameters/properties can be cumbersome in the relational model.

Even though an ORM should handle the schema, it's useful to consider designs so as to know what to expect from the ORM. One way of handling a variable number of properties is to have entity-attribute-value tables. However, this approach has several issues, such as it doesn't handle types very well (the values must have the same type in the DB, but in all likelihood have different types as properties). A more appropriate approach is to model inheritance relationally by giving each class its own table, with a column that refers to the parent table. The parent table should include a column that identifies the particular descendent (it functions both to identify the runtime class and identifies which table holds additional data). In particular, there'd be a base table for Pricing and a separate table for each pricing descendent. (To cut down on tables, this might be a case where you'd implement is-a-member as has-been-a-member-for(0), so as not to introduce a separate table for is-a-member. Alternatively, you could not have tables for nullary pricings.) Course->pricings is a one-to-many relationship, so you'd have a table associating the two; if it's a sequence, the table would also record the sequence position for each pricing. All together, the schema would look something like:

```<code>CREATE TABLE courses (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    price DECIMAL(19, 4),
    ...
);

CREATE TABLE pricings (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    name ENUM('Always', 'NotAMember', 'Indebted', 'MemberFor')
);

CREATE TABLE courses_pricings (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    course INT UNSIGNED NOT NULL,
    pricing INT UNSIGNED NOT NULL,
    position INT UNSIGNED NOT NULL,
    FOREIGN KEY (`course_pricing`) REFERENCES `courses` (`id`),
    FOREIGN KEY (`pricing`) REFERENCES `pricings` (`id`)
);

CREATE TABLE memberFor (
    pricing INT UNSIGNED NOT NULL,
    `days` INT NOT NULL, -- use whatever unit allows for the finest-grain required by pricing; the MemberFor class can convert it as appropriate
    FOREIGN KEY (`pricing`) REFERENCES `pricings` (`id`)
);
</code>```

The schema could be denormalized (if profiling warrants) by combining pricings and courses_pricings.

Body:
Definitely implement the rules in PHP. SQL is for data, not business logic or other behavior. There is a third option, implement rules as expressions stored in the DB and have PHP evaluate them, but that way madness lies. The rules should be pre-defined, not defined when configuring a course's pricing in a domain-specific language.

Early on, you should decide whether to model the different price options as discounts (an amount is subtracted from the course's base price) or differential pricing (price is associated with each rule; a course has no base price). You can also combine the two by supporting relative pricings (e.g. "75%", "-$50") in addition to absolute pricings (e.g. "$300"), in which case courses have base prices, but they're not referenced outside of pricings. Which you pick shouldn't have a major impact overall, but will have small affects and will inform the design.

As for implementation, you could use something like the strategy pattern, with pricings like strategies and courses like contexts. The primary Pricing method (e.g. __invoke()) would take a course & a user and return an amount or, if the user isn't eligible for the pricing, NULL. Alternatively, have two primary methods: one to tell whether the user is eligible for the pricing, and another to return the amount (less strategy-like, but might make more sense for your overall design). In addition to the special pricings requested by the client, you'd have an Always pricing that represents no discount and is always applicable. A Course has a collection of pricings (which is one thing that makes this not follow the strategy pattern). Determining whether a user is in good standing (i.e. doesn't owe anything on the annual fee) would be handled by a User method (or by a method of whatever class is responsible for managing a user's transactions, e.g. Account: $user->account->inGoodStanding()).

To determine the final price, you'll need to determine a strategy precedence. One option is to define in code, implicitly or explicitly, a total order for pricings (Always would be the minimum). Another would be to rely on a sequence type for Course->pricings, and apply the pricings in this sequence. To ensure every course has a final price, end the sequence with an Always. With Pricing::__invoke() returning NULL, you can think of this as a coalescing operation. The latter precedence is easier to implement and more flexible, but potentially allows for errors (courses without an applied pricing, or with unreachable pricings). You can prevent some (all?) precedence errors by having & using a course's base price as a fallback instead of an Always sentinal.

Note that some pricings could be based on others (e.g. is-a-member could be implemented as has-been-a-member-for(0)). Whether & when to do this depends on other design details. Be careful to follow proper OO principles if you do this. For example, use inheritance only if overridden properties are effectively immutable so as not to violate LSP. If not, you could end up with an is-a-member that has a non-zero period.

When it comes to the DB design, you can leave it to an ORM. Since data outlasts applications, you want to use an ORM that properly accounts for object-relational impedance mismatch (or procedural-relational impedance mismatch, as strategies can be viewed as procedures encapsulated by objects), which is the biggest problem with this approach. Specifically, different strategies have different arities, and dealing with a variable number of parameters/properties can be cumbersome in the relational model.

Even though an ORM should handle the schema, it's useful to consider designs so as to know what to expect from the ORM. One way of handling a variable number of properties is to have entity-attribute-value tables. However, this approach has several issues, such as it doesn't handle types very well (the values must have the same type in the DB, but in all likelihood have different types as properties). A more appropriate approach is to model inheritance relationally by giving each class its own table, with a column that refers to the parent table. The parent table should include a column that identifies the particular descendent (it functions both to identify the runtime class and identifies which table holds additional data). In particular, there'd be a base table for Pricing and a separate table for each pricing descendent. (To cut down on tables, this might be a case where you'd implement is-a-member as has-been-a-member-for(0), so as not to introduce a separate table for is-a-member. Alternatively, you could not have tables for nullary pricings.) Course->pricings is a one-to-many relationship, so you'd have a table associating the two; if it's a sequence, the table would also record the sequence position for each pricing. All together, the schema would look something like:

CREATE TABLE courses (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    price DECIMAL(19, 4),
    ...
);

CREATE TABLE pricings (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    name ENUM('Always', 'NotAMember', 'Indebted', 'MemberFor')
);

CREATE TABLE courses_pricings (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    course INT UNSIGNED NOT NULL,
    pricing INT UNSIGNED NOT NULL,
    position INT UNSIGNED NOT NULL,
    FOREIGN KEY (`course_pricing`) REFERENCES `courses` (`id`),
    FOREIGN KEY (`pricing`) REFERENCES `pricings` (`id`)
);

CREATE TABLE memberFor (
    pricing INT UNSIGNED NOT NULL,
    `days` INT NOT NULL, -- use whatever unit allows for the finest-grain required by pricing; the MemberFor class can convert it as appropriate
    FOREIGN KEY (`pricing`) REFERENCES `pricings` (`id`)
);

The schema could be denormalized (if profiling warrants) by combining pricings and courses_pricings.


问:
rand() gives same numbers again for a small range
I'm trying to make sort of a game where I have a a grid of 20x20 and I display a player (P), a target (T) and three enemies (X). All these have an X and a Y coordinate which are assigned using rand(). The problem is that if I try to get more points in the game (refills for energy etc) they overlap with one or more of the other points because the range is small(1 to 20 inclusive).

These are my variables and how I'm assigning them values:
(the COORD is a struct with just an X and a Y)

```<code>const int gridSize = 20;
COORD player;
COORD target;
COORD enemy1;
COORD enemy2;
COORD enemy3;

//generate player
srand ( time ( NULL ) );
spawn(&player);
//generate target
spawn(&target);
//generate enemies
spawn(&enemy1);
spawn(&enemy2);
spawn(&enemy3);

void spawn(COORD *point)
{
    //allot X and Y coordinate to a point
    point->X = randNum();
    point->Y = randNum();
}

int randNum()
{
    //generate a random number between 1 and gridSize
    return (rand() % gridSize) + 1;
}
</code>```

I want to add more things to the game but the probability of overlap increases when I do that. Is there any way to fix this?

答:
The simplest solution to this problem has been quoted in previous answers: it is to make a list of random values alongside every one of your 400 cells, and then, to sort this random list. Your list of cells will be sorted as the random list, and this way, will be shuffled.

This method has the advantage of totally avoiding the overlapping of randomly selected cells.

The disadvantage is that you have to compute a random value on a separate list for each of your cells. So, you'd rather not doing it while the game has started.

Here is an example of how you can do it:

```<code>#include <algorithm>
#include <iostream>
#include <vector>

#define NUMBER_OF_SPAWNS 20
#define WIDTH 20
#define HEIGHT 20

typedef struct _COORD
{
  int x;
  int y;
  _COORD() : x(0), y(0) {}
  _COORD(int xp, int yp) : x(xp), y(yp) {}
} COORD;

typedef struct _spawnCOORD
{
  float rndValue;
  COORD*coord;
  _spawnCOORD() : rndValue(0.) {}
} spawnCOORD;

struct byRndValue {
  bool operator()(spawnCOORD const &a, spawnCOORD const &b) {
    return a.rndValue < b.rndValue;
  }
};

int main(int argc, char** argv)
{
  COORD map[WIDTH][HEIGHT];
  std::vector<spawnCOORD>       rndSpawns(WIDTH * HEIGHT);

  for (int x = 0; x < WIDTH; ++x)
    for (int y = 0; y < HEIGHT; ++y)
      {
        map[x][y].x = x;
        map[x][y].y = y;
        rndSpawns[x + y * WIDTH].coord = &(map[x][y]);
        rndSpawns[x + y * WIDTH].rndValue = rand();
      }

  std::sort(rndSpawns.begin(), rndSpawns.end(), byRndValue());

  for (int i = 0; i < NUMBER_OF_SPAWNS; ++i)
    std::cout << "Case selected for spawn : " << rndSpawns[i].coord->x << "x"
              << rndSpawns[i].coord->y << " (rnd=" << rndSpawns[i].rndValue << ")\n";
  return 0;
}
</code>```

Result:

```<code>root@debian6:/home/eh/testa# ./exe
Case selected for spawn : 11x15 (rnd=6.93951e+06)
Case selected for spawn : 14x1 (rnd=7.68493e+06)
Case selected for spawn : 8x12 (rnd=8.93699e+06)
Case selected for spawn : 18x13 (rnd=1.16148e+07)
Case selected for spawn : 1x0 (rnd=3.50052e+07)
Case selected for spawn : 2x17 (rnd=4.29992e+07)
Case selected for spawn : 9x14 (rnd=7.60658e+07)
Case selected for spawn : 3x11 (rnd=8.43539e+07)
Case selected for spawn : 12x7 (rnd=8.77554e+07)
Case selected for spawn : 19x0 (rnd=1.05576e+08)
Case selected for spawn : 19x14 (rnd=1.10613e+08)
Case selected for spawn : 8x2 (rnd=1.11538e+08)
Case selected for spawn : 7x2 (rnd=1.12806e+08)
Case selected for spawn : 19x15 (rnd=1.14724e+08)
Case selected for spawn : 8x9 (rnd=1.16088e+08)
Case selected for spawn : 2x19 (rnd=1.35497e+08)
Case selected for spawn : 2x16 (rnd=1.37807e+08)
Case selected for spawn : 2x8 (rnd=1.49798e+08)
Case selected for spawn : 7x16 (rnd=1.50123e+08)
Case selected for spawn : 8x11 (rnd=1.55325e+08)
</code>```

Just change NUMBER_OF_SPAWNS to get more or less random cells, this will not change the computation time required for the task.

Body:
The simplest solution to this problem has been quoted in previous answers: it is to make a list of random values alongside every one of your 400 cells, and then, to sort this random list. Your list of cells will be sorted as the random list, and this way, will be shuffled.

This method has the advantage of totally avoiding the overlapping of randomly selected cells.

The disadvantage is that you have to compute a random value on a separate list for each of your cells. So, you'd rather not doing it while the game has started.

Here is an example of how you can do it:

#include <algorithm>
#include <iostream>
#include <vector>

#define NUMBER_OF_SPAWNS 20
#define WIDTH 20
#define HEIGHT 20

typedef struct _COORD
{
  int x;
  int y;
  _COORD() : x(0), y(0) {}
  _COORD(int xp, int yp) : x(xp), y(yp) {}
} COORD;

typedef struct _spawnCOORD
{
  float rndValue;
  COORD*coord;
  _spawnCOORD() : rndValue(0.) {}
} spawnCOORD;

struct byRndValue {
  bool operator()(spawnCOORD const &a, spawnCOORD const &b) {
    return a.rndValue < b.rndValue;
  }
};

int main(int argc, char** argv)
{
  COORD map[WIDTH][HEIGHT];
  std::vector<spawnCOORD>       rndSpawns(WIDTH * HEIGHT);

  for (int x = 0; x < WIDTH; ++x)
    for (int y = 0; y < HEIGHT; ++y)
      {
        map[x][y].x = x;
        map[x][y].y = y;
        rndSpawns[x + y * WIDTH].coord = &(map[x][y]);
        rndSpawns[x + y * WIDTH].rndValue = rand();
      }

  std::sort(rndSpawns.begin(), rndSpawns.end(), byRndValue());

  for (int i = 0; i < NUMBER_OF_SPAWNS; ++i)
    std::cout << "Case selected for spawn : " << rndSpawns[i].coord->x << "x"
              << rndSpawns[i].coord->y << " (rnd=" << rndSpawns[i].rndValue << ")\n";
  return 0;
}

Result:

root@debian6:/home/eh/testa# ./exe
Case selected for spawn : 11x15 (rnd=6.93951e+06)
Case selected for spawn : 14x1 (rnd=7.68493e+06)
Case selected for spawn : 8x12 (rnd=8.93699e+06)
Case selected for spawn : 18x13 (rnd=1.16148e+07)
Case selected for spawn : 1x0 (rnd=3.50052e+07)
Case selected for spawn : 2x17 (rnd=4.29992e+07)
Case selected for spawn : 9x14 (rnd=7.60658e+07)
Case selected for spawn : 3x11 (rnd=8.43539e+07)
Case selected for spawn : 12x7 (rnd=8.77554e+07)
Case selected for spawn : 19x0 (rnd=1.05576e+08)
Case selected for spawn : 19x14 (rnd=1.10613e+08)
Case selected for spawn : 8x2 (rnd=1.11538e+08)
Case selected for spawn : 7x2 (rnd=1.12806e+08)
Case selected for spawn : 19x15 (rnd=1.14724e+08)
Case selected for spawn : 8x9 (rnd=1.16088e+08)
Case selected for spawn : 2x19 (rnd=1.35497e+08)
Case selected for spawn : 2x16 (rnd=1.37807e+08)
Case selected for spawn : 2x8 (rnd=1.49798e+08)
Case selected for spawn : 7x16 (rnd=1.50123e+08)
Case selected for spawn : 8x11 (rnd=1.55325e+08)

Just change NUMBER_OF_SPAWNS to get more or less random cells, this will not change the computation time required for the task.


问:
Error handling in math library functions
When writing a library function, such as

```<code>double getAvg(double[]);
</code>```

how should one handle the empty array?

(Note that, mathematically speaking the avg of an empty set is undefined.)

答:
Whatever you do, document it. If users do not like the default behaviour you provide, they can then adapt your function to their needs.

Here are a couple of possibilities, sorted from best to least preferred (in my opinion).

There is no sensible value in these cases, so we need to return the absence of a value. This might be a double* or double? with a null pointer, or a Maybe Double type or a Optional<double> object, depending on your language. These techniques have the benefit of lifting the absence of a value to the type system, so you can enforce that the user checks for the error condition.

This is a logic error, so you should throw an exception, or use whatever mechanism is idiomatic in your language to specify an error. E.g. in Go, you would return multiple arguments with one being an error code, whereas you might set errno in C. If users would rather have a certain default value, they can then catch the exception.

Floating point numbers have a sane default value that could be returned in such cases. If users do not like the default value, they can explicitly check for the error-inducing input, and provide their own error behaviour.

the default should be 0, since this is generally the default for numbers.

the default should be NaN (= 0/0) to signal the absence of a value. If the language supports IEEE floating point operations, this will quickly “poison” all computations using that value. Note that NaN is a valid return value if any of the inputs was also NaN.


问:
Can programs of different languages communicate information without file io?
Is it possible to write a C++ program that, say, passes an int array to a java program without writing it to a file?

Motivation for question: I was wondering what matlab is and how it came to be an application that was written in several different languages (as opposed to being available in different languages i.e., there is a version of it in C++, Java, etc... that contains the same features).

答:
Yes. Each process can communicate with another using a thing called IPC, or Inter Process Communication (unsurprisingly!). There are many different forms of IPC, file IO being the one used by a fair few unix programs, but you can use sockets, named pipes or memory-maps, or even a database (using something along the lines of the blackboard architectural pattern).

The language used to create a process is irrelevant (except for its support to access the same IPC mechanism).


答:
Nearly all languages that are worth writing in have some way of interfacing with a C dynamic library. In java that is done with the Java Native Interface or by hosting the JVM in memory like a scripting engine of sorts.

With matlab there is a similar setup to java's.

From C you would call Engine engine = engopen(NULL); and use engine to send commands to the matlab process using either a COM service or a a set of pipes.

Title: Can programs of different languages communicate information without file io?

Body:
Is it possible to write a C++ program that, say, passes an int array to a java program without writing it to a file?

Motivation for question: I was wondering what matlab is and how it came to be an application that was written in several different languages (as opposed to being available in different languages i.e., there is a version of it in C++, Java, etc... that contains the same features).


答:
Yes. The general answer is that they have some kind of shared binary interface. Typically the de facto C API. To oversimplify it a bit, this means writing a function in language A that calls a function written in C, and that function written in C then calls a function written in language B. Some useful examples:

Lua is a scripting language designed to be embedded within C code. The most famous use case is a video game with the engine written in C but all the high-level stuff scripted in Lua.

Some languages (including Java, Python, and way more) contain a special FFI (foreign function interface) library for the sole purpose of calling C functions.

As others have pointed out, almost all IPC (interprocess communication) mechanisms and network communication protocols are language independent. They all revolve around sending an arbitrary series of bytes, leaving it up to the recipient to make sense of those bytes.

I'm failing to find any definitive information, but random people on the internet seem to think that MATLAB's UI is written in Java and uses IPC to talk to the interpreter written in C++.


问:
Is an interface considered 'empty' if it inherits from other interfaces?
Empty interfaces are generally consider bad practice, as far as I can tell - especially where things like attributes are supported by the language.

However, is an interface considered 'empty' if it inherits from other interfaces?

```<code>interface I1 { ... }
interface I2 { ... } //unrelated to I1

interface I3
    : I1, I2
{
    // empty body
}
</code>```

Anything that implements I3 will need to implement I1 and I2, and objects from different classes that inherit I3 can then be used interchangeably (see below), so is it right to call I3 empty? If so what would be a better way to architecture this?

```<code>// with I3 interface
class A : I3 { ... }
class B : I3 { ... }

class Test {
    void foo() {
        I3 something = new A();
        something = new B();
        something.SomeI1Function();
        something.SomeI2Function();
    }
}

// without I3 interface
class A : I1, I2 { ... }
class B : I1, I2 { ... }

class Test {
    void foo() {
        I1 something = new A();
        something = new B();
        something.SomeI1Function();
        something.SomeI2Function(); // we can't do this without casting first
    }
}
</code>```

答:
If there were particular importance in having a class implement both interfaces, then I see nothing wrong with creating a third interface that inherits from both.  However, I would be careful to not fall into the trap of overengineering things.  A class could inherit from one or the other, or both.  Unless my program had plenty of classes in these three cases, it is a little much to create an interface for both, and certainly not if those two interfaces had no relation to one another (no IComparableAndSerializable interfaces please).

I remind you that you can create an abstract class as well that inherits from both interfaces, and you can use that abstract class in place of I3.  I think it would be wrong to say that you shouldn't do it, but you should at the very least have a good reason.


答:
Anything that implements I3 will need to implement I1 and I2, and objects from different classes that inherit I3 can then be used interchangeably (see below), so is it right to call I3 empty? If so what would be a better way to architecture this?

"Bundling" I1 and I2 into I3 offers a nice (?) shortcut, or some sort of syntax sugar for wherever you'd like both to be implemented.

The problem with this approach is that you can't stop other developers from explicitly implementing I1 and I2 side by side, but it doesn't work both ways - while : I3 is equivalent of : I1, I2, : I1, I2 is not an equivalent of : I3. Even if they're functionally identical, a class that supports both I1 and I2 will not be detected as supporting I3.

This means that you're offering two ways of accomplishing the same thing - "manual" and "sweet" (with your syntax sugar). And it can have a bad impact on code consistency. Offering 2 different ways to accomplish the same thing here, there, and in another place results in 8 possible combinations already :)

```<code>void foo() {
    I1 something = new A();
    something = new B();
    something.SomeI1Function();
    something.SomeI2Function(); // we can't do this without casting first
}
</code>```

OK, you can't. But perhaps it's actually a good sign?

If I1 and I2 imply different responsibilities (otherwise there would be no need to separate them in the first place), then maybe foo() is wrong to try and make something perform two different responsibilities in one go?

In other words, it could be that foo() itself violates the principle of Single Responsibility, and the fact that it requires casting and runtime type checks to pull it off is a red flag alarming us about it.

EDIT:

If you insisted on ensuring that foo takes something that implements I1 and I2, you could pass them as separate parameters:

```<code>void foo(I1 i1, I2 i2)
</code>```

And they could be the same object:

```<code>foo(something, something);
</code>```

What does foo care if they're the same instance or not?

But if it does care (eg. because they're not stateless), or you just think this looks ugly, one could use generics instead:

```<code>void Foo<T>(T something) where T: I1, I2
</code>```

Now generic constraints take care of the desired effect while not polluting the outside world with anything. This is idiomatic C#, based on compile-time checks, and it feels more right overall.

I see I3 : I2, I1 somewhat as an effort to emulate union types in a language that doesn't support it out of the box (C# or Java don't, whereas union types exist in functional languages).

Trying to emulate a construct that's not really supported by the language is often clunky. Similarly, in C# you can use extension methods and interfaces if you want to emulate mixins. Possible? Yes. Good idea? I'm not sure.

Title: Is an interface considered 'empty' if it inherits from other interfaces?

Body:
Empty interfaces are generally consider bad practice, as far as I can tell - especially where things like attributes are supported by the language.

However, is an interface considered 'empty' if it inherits from other interfaces?

```<code>interface I1 { ... }
interface I2 { ... } //unrelated to I1

interface I3
    : I1, I2
{
    // empty body
}
</code>```

Anything that implements I3 will need to implement I1 and I2, and objects from different classes that inherit I3 can then be used interchangeably (see below), so is it right to call I3 empty? If so what would be a better way to architecture this?

```<code>// with I3 interface
class A : I3 { ... }
class B : I3 { ... }

class Test {
    void foo() {
        I3 something = new A();
        something = new B();
        something.SomeI1Function();
        something.SomeI2Function();
    }
}

// without I3 interface
class A : I1, I2 { ... }
class B : I1, I2 { ... }

class Test {
    void foo() {
        I1 something = new A();
        something = new B();
        something.SomeI1Function();
        something.SomeI2Function(); // we can't do this without casting first
    }
}
</code>```

Body:
Anything that implements I3 will need to implement I1 and I2, and objects from different classes that inherit I3 can then be used interchangeably (see below), so is it right to call I3 empty? If so what would be a better way to architecture this?

"Bundling" I1 and I2 into I3 offers a nice (?) shortcut, or some sort of syntax sugar for wherever you'd like both to be implemented.

The problem with this approach is that you can't stop other developers from explicitly implementing I1 and I2 side by side, but it doesn't work both ways - while : I3 is equivalent of : I1, I2, : I1, I2 is not an equivalent of : I3. Even if they're functionally identical, a class that supports both I1 and I2 will not be detected as supporting I3.

This means that you're offering two ways of accomplishing the same thing - "manual" and "sweet" (with your syntax sugar). And it can have a bad impact on code consistency. Offering 2 different ways to accomplish the same thing here, there, and in another place results in 8 possible combinations already :)

void foo() {
    I1 something = new A();
    something = new B();
    something.SomeI1Function();
    something.SomeI2Function(); // we can't do this without casting first
}

OK, you can't. But perhaps it's actually a good sign?

If I1 and I2 imply different responsibilities (otherwise there would be no need to separate them in the first place), then maybe foo() is wrong to try and make something perform two different responsibilities in one go?

In other words, it could be that foo() itself violates the principle of Single Responsibility, and the fact that it requires casting and runtime type checks to pull it off is a red flag alarming us about it.

EDIT:

If you insisted on ensuring that foo takes something that implements I1 and I2, you could pass them as separate parameters:

void foo(I1 i1, I2 i2)

And they could be the same object:

foo(something, something);

What does foo care if they're the same instance or not?

But if it does care (eg. because they're not stateless), or you just think this looks ugly, one could use generics instead:

void Foo<T>(T something) where T: I1, I2

Now generic constraints take care of the desired effect while not polluting the outside world with anything. This is idiomatic C#, based on compile-time checks, and it feels more right overall.

I see I3 : I2, I1 somewhat as an effort to emulate union types in a language that doesn't support it out of the box (C# or Java don't, whereas union types exist in functional languages).

Trying to emulate a construct that's not really supported by the language is often clunky. Similarly, in C# you can use extension methods and interfaces if you want to emulate mixins. Possible? Yes. Good idea? I'm not sure.


问:
Are private members useful anymore?
Watchpoints and data break points make it possible to watch the changes of a value in memory in many languages.

Much of the justification I have seen for getters and setters and private variables hinges on the getters and setters being clear places in which break points can be set.

If watchpoints and data breakpoints make the break points on getters and setters a moot point, should I be using private members in my code anymore if I trust the other programmers on my team?

答:
Getters and setters have nothing to do with breakpoints, although they may be helpful in this regard.

They are designed to allow the client to obtain and change the private data members of a class, while encapsulating what the class actually does to the data behind closed doors.

Title: Are private members useful anymore?


答:
I assume you mean "get rid of accessors and make private members public"... well, from a design point of view, a getter/setter is not doing much more than a public variable anyway, just with more layers.

Now, a good class design would not even begin to consider exposing a variable at all, it instead adds methods that apply to the internal state of the object (said state being expressed in terms of one or more variables) to perform logical operations on the object.

So really, getters and setters are a smell and should be removed. If you think of a class as a bundle of variables then you're not thinking right anyway, fix that first.

Once fixed, you find you'll have no getters or setters anyway and all variables will be private. Then you can put your breakpoints on the methods that operate on the class.

Title: Are private members useful anymore?

Body:
Watchpoints and data break points make it possible to watch the changes of a value in memory in many languages.

Much of the justification I have seen for getters and setters and private variables hinges on the getters and setters being clear places in which break points can be set.

If watchpoints and data breakpoints make the break points on getters and setters a moot point, should I be using private members in my code anymore if I trust the other programmers on my team?


问:
Design pattern for different code behaviors according to different clients
At my company, we have a solution composed of a WinForm (multiple per client) and an API (one per client). This solution is deployed on different clients that require the solution to behave differently according to their desires. The same code base must support UI customizations (client logo, buttons visibility) and functionality customizations (calling the same WebMethod with different flags).

Currently we manage this flexibility on the WinForm side by having an Organization class that contains all these customizations (flags). The API is totally client-agnostic. Thus, the WinForm's methods look like this:

```<code>this.Logo = CurrentOrganization.LogoImage;

API.GetProducts(Organization.UsesPagination);
</code>```

In the past, we had conditional build directives scattered among the code:

```<code>#IF CLIENT_A
    API.GetProductsWithPagination();
#ELSE
    API.GetProducts();
#ENDIF
</code>```

Today, we have a single zone with those conditional build directives that, according to the build configuration, instantiates the required Organization class. Afterwards, there are no more IFs, parameter passing.

I'm a bit worried this is not the best design or the most maintainable solution. I studied the State pattern... I guess the Organization is my strategy object, since it tells other methods how they should behave through flags.

Is there a better way?

Storing configurations on a DB table? (requires more requests to the API, which costs time)

Storing configurations on a *.config files? (someone can easily change the app behavior by editing the file)

答:
I would strive for data-driven design. This means that your code is driven by customer specific data. This data may be stored in database or configuration files or whatever suits you best. This way you don't have to build different binaries for each customer with the conditional build directives.

In cases where you need different behavior for different customers you can look up the desired behavior from the customer data and use Strategy pattern switch it during runtime.


问:
What is the right testing strategy in Agile Scrum/Kanban teams?
The problem is:

The team , I am working in has 10 developers to 2 testers ratio which means we are going to churn out code more quickly than it is "Test" done.

So, What should be the right approach to track activities in such scenarios according to agile experts?

My fear is that soon the day will come , when there is a lot of stuff which will be called as "Done" in previous sprints (with no testing done) but when it actually comes to testing, there might be some potential defects.

How can I track the efforts seamlessly? Should testing be part of "Done Definition"? What are the pitfalls if it is not?

As per me, it is sort of 'Waterfall' as you are calling stories "Done" before it is actually functionally tested.

答:
Yes, testing absolutely should be part of the definition of "Done". Without question. </p>

<p>From a purely agile standpoint, the right approach is for everyone on the team to contribute toward writing tests. The tester would be the one coordinating the effort, but it is the responsibility of the entire team to make sure the software is properly tested. </p>

Body:
Yes, testing absolutely should be part of the definition of "Done". Without question.

From a purely agile standpoint, the right approach is for everyone on the team to contribute toward writing tests. The tester would be the one coordinating the effort, but it is the responsibility of the entire team to make sure the software is properly tested.


问:
How do I handle setters on immutable fields?
I have a class with two readonly int fields.  They are exposed as properties:

```<code>public class Thing
{
    private readonly int _foo, _bar;

    /// <summary> I AM IMMUTABLE. </summary>
    public Thing(int foo, int bar)
    {
        _foo = foo;
        _bar = bar;
    }

    public int Foo { get { return _foo; } set { } }

    public int Bar { get { return _bar; } set { } }
}
</code>```

However, that means that the following is perfectly legal code:

```<code>Thing iThoughtThisWasMutable = new Thing(1, 42);

iThoughtThisWasMutable.Foo = 99;  // <-- Poor, mistaken developer.
                                  //     He surely has bugs now. :-(
</code>```

The bugs that come from assuming that would work are sure to be insidious.  Sure, the mistaken developer should have read the docs.  But that doesn't change the fact that no compile- or run-time error warned him about the problem.

How should the Thing class be changed so that devs are less likely to make the above mistake?

Throw an exception?  Use a getter method instead of a property?

答:
Why make that code legal?

Take out the set { } if it does nothing.

This is how you define a read only public property:

```<code>public int Foo { get { return _foo; } }
</code>```

Body:
Why make that code legal?

Take out the set { } if it does nothing.

This is how you define a read only public property:

public int Foo { get { return _foo; } }


答:
You could just get rid of the setters. They don't do anything, they will confuse users and they will lead to bugs. However, you could instead make them private and thus get rid of the backing variables, simplifying your code:</p>

```<code>public class Thing
{
    public Thing(int foo, int bar)
    {
        Foo = foo;
        Bar = bar;
    }

    public int Foo { get; private set; }

    public int Bar { get; private set; }
}
</code>```

Title: How do I handle setters on immutable fields?

Body:
I have a class with two readonly int fields.  They are exposed as properties:

```<code>public class Thing
{
    private readonly int _foo, _bar;

    /// <summary> I AM IMMUTABLE. </summary>
    public Thing(int foo, int bar)
    {
        _foo = foo;
        _bar = bar;
    }

    public int Foo { get { return _foo; } set { } }

    public int Bar { get { return _bar; } set { } }
}
</code>```

However, that means that the following is perfectly legal code:

```<code>Thing iThoughtThisWasMutable = new Thing(1, 42);

iThoughtThisWasMutable.Foo = 99;  // <-- Poor, mistaken developer.
                                  //     He surely has bugs now. :-(
</code>```

The bugs that come from assuming that would work are sure to be insidious.  Sure, the mistaken developer should have read the docs.  But that doesn't change the fact that no compile- or run-time error warned him about the problem.

How should the Thing class be changed so that devs are less likely to make the above mistake?

Throw an exception?  Use a getter method instead of a property?

Body:
You could just get rid of the setters. They don't do anything, they will confuse users and they will lead to bugs. However, you could instead make them private and thus get rid of the backing variables, simplifying your code:

public class Thing
{
    public Thing(int foo, int bar)
    {
        Foo = foo;
        Bar = bar;
    }

    public int Foo { get; private set; }

    public int Bar { get; private set; }
}


问:
Fine grained search over a large dataset
I have roughly 4 million records per day and have to keep 7 years worth online, so we are looking at 10.2 billion records that I need to be able to search through. The users are expecting that the search will be quick enough for a UI, results in 3-5s

Due to politics out of my control, I can't use an off the shelf database solution because it means I will have to give the database to another team to manage (don't ask) which means I loose the ability to optimize hardware and software as they have a one-size-fits-all service for databases and charge (internally) by the GB. I'm sure I am going to get comments suggesting I make the point, I already have and management understand what they are asking me to do is ridiculous.

I have been looking at using Lucene as the crux of my solution. Storing the actual data partitioned by type and by day in flat files. Then using a Lucene document to index some of the fields that are searched by, with the only "Stored" field being the id of the record (so that I can read it from the flat file)

I am not exactly clued up on Lucene or hard drives, but as per my understanding, there will be initial IO/seeking time for searching the index, then when I have all the Lucene document IDs, I read the documents which will incur further IO/seeking time, then I read the actual record from the flat flat...I can't imagine, given the size of the dataset, that this will be very quick, which I am slightly worried about?

Lucene has a max document size of 2.1billion per index, so I will require multiple indicies here.

Does this approach, on the face of it, look like it could work?

The data I am storing is event-action data. Most of the queries will be grouping by event id and getting the last event-action details for a particular event. Some of the queries will be analysing large sets events and their individual event-actions.

答:
Ignoring all the technical details this is an organizational/management problem and needs to be solved by the management of your organization.

Your manager has to be willing to kick the problem upstairs and/or get his users to raise the problem at a high level.

At your level put together or request an estimate for doing this with Oracle and Oracle hardware. Then put together a realistic estimate for a Hadoop cluster.

Despite the hype these clusters do not come cheap (You probably need something like 18 8 processor nodes with 64GB memory and 4 x 2 TB disks spread over three racks then another 4 nodes for the catalog etc.). DO NOT underestimate ; if you win you will have to implement it.


答:
With C#5 and before, we were faced with two options for immutable fields exposed via a getter:

Create a read-only backing variable and return that via a manual getter. This option is secure (one must explicitly remove the readonly to destroy the immutability. It created lots of boiler-plate code though.

Use an auto-property, with a private setter. This creates simpler code, but it's easier  to accidentally break the immutability.

With C# 6 though (available in VS2015, which was released yesterday), we now get the best of both worlds: read-only auto properties. This allows us to simplify the OP's class to:

```<code>public class Thing
{
    /// <summary> I AM IMMUTABLE. </summary>
    public Thing(int foo, int bar)
    {
        Foo = foo;
        Bar = bar;
    }

    public int Foo { get; }
    public int Bar { get; }
}
</code>```

The Foo = foo and Bar = bar lines  are only valid in the constructor (which achieves the robust read-only requirement) and the backing field is implied, rather than having to be explicitly defined (which achieves the simpler code).

Body:
With C#5 and before, we were faced with two options for immutable fields exposed via a getter:

Create a read-only backing variable and return that via a manual getter. This option is secure (one must explicitly remove the readonly to destroy the immutability. It created lots of boiler-plate code though.

Use an auto-property, with a private setter. This creates simpler code, but it's easier  to accidentally break the immutability.

With C# 6 though (available in VS2015, which was released yesterday), we now get the best of both worlds: read-only auto properties. This allows us to simplify the OP's class to:

public class Thing
{
    /// <summary> I AM IMMUTABLE. </summary>
    public Thing(int foo, int bar)
    {
        Foo = foo;
        Bar = bar;
    }

    public int Foo { get; }
    public int Bar { get; }
}

The Foo = foo and Bar = bar lines  are only valid in the constructor (which achieves the robust read-only requirement) and the backing field is implied, rather than having to be explicitly defined (which achieves the simpler code).


问:
What is a simple way to let a user select a folder from a tree?
I have a Python-Flask app in which users can place files into a folder.
As of now the directory structure is something like:

```<code>/app
    /storage
    /templates
    .
    .
    .
    server.py
</code>```

The user can create directories and subdirectories within storage to organize files.

So far I am making AJAX calls to the server to get details of folders etc. and populate a dropdown list from which users can traverse the tree. It works, but it just doesn't feel right. What other approach could I take?

The major issue that I'm hoping to address (and what I'm doing right now):

There is a lag between when the user selects a folder to when it's contents are shown. Of course I don't expect it to be as fast as opening directories on a local file system but it'd be nice to improve UX there.

Current solution: I'm loading information about the contents of all the subdirectories as soon as a directory is selected. I can then show contents of the subdirectory as soon as it is selected.

Suppose the directory structure is:

```<code>/foo
    /bar
        /sub
        hello.py
        world.py
    /car
        hello.c
        world.c
</code>```

I'm fetching information about files/subdirectories within bar and car as soon as foo is opened. This helps in showing them contents as soon as bar or car is selected.

Advantage: UX is good

Disadvantage: Transfers too much unnecessary data from the server. And as I'm actually accessing the disk to open each subdirectory this may become slow if many subdirectories are present!

Also, I'm not sure how well this will scale, if it is ever necessary.

答:
Clearly, you have to make server requests at some point to get the user's stuff. For optimal UX, assuming it's impractical to load everything upfront, it'd be silly not to use some kind of AJAX request. So the real question is: What should the granularity of your requests be?

The correct answer has more to do with UX than code quality, and will depend very heavily on how your audience tends to use your app. But, since you asked in the first place, you almost certainly want to get more in each request than just the contents of the file/folder the user clicked on. Some prefetching rules you may wish to consider when the user opens a folder:

Track when the user last accessed each file, so you can prefetch the contents of the most recently accessed ones.

Track how many times the user has opened each file, so you can prefetch the contents of the most frequently accessed ones.

Track the creation times for each file/folder, so you can prefetch the most recently created stuff.

Unconditionally prefetch any super-tiny files in the current folder.

If any of the files are "shared" with other users, those might be considered a high priority for prefetching.

In reality, you'll probably end up with a weighted average of several of these rules.

Of course, the first thing to do is talk to your users/testers to see if there's any super low-hanging fruit that everyone but you knows about. It's likely that one or two of these rules will immediately strike them as an obvious quick win.

Finally, once you have some prefetching, set up some kind of logging that tells you every time a user accesses something you did not prefetch. That's the most reliable way to find out where your current ruleset could be improved, without the users having to figure it out for you.


问:
Should client side have a log?
The client side of my application is written in VB.Net, it accesses a java server.
Server logs every request that was made by client, client shows every exception to the user (with an option to send it to support).

The question is: would you add logs to the client side?
If yes, what information does it make sense to write to the client log?

答:
Every code which is complicated enough that it won't be straigtforward to debug should create logs. The fact that it's running on client side is irrelevant.

You can skip logging if:

You are not expecting to support the application, that is you are developing a prototype or abandonware.

The logic is extremely simple and consists of 1:1 mapping of server calls. Aside theoretical examples good for tutorials, I can't imagine any concrete example of an app which does something useful while being in this case.

You're paid per hour of support and your company has no respect towards their customers. Longer debugging means more money, short term. Absence of logs means more debugging time.

Title: Should client side have a log?


答:
I have integrated with a team that used a pure desktop application with the server meaning the "database" - for them it made complete sense to have a client side log because that is where all the code was executed. There was no other way to debug an issue if it ever occurred. In terms of "what" to log - it is subjective and based pure on what you will need for debuging? This is never easy to answer even if you were logging on the server.

But these are the considerations I would keep in mind since you are NOT on a server,

You have no way to "protect" the logs from an unauthorized edit, at least not the level of confidece you could have in a server.

You need to be extra careful about logging sensitive information as it could be misused.

Disk space on the client side is not in your control - so make sure you don't exhaust an already overly crowded hard disk of your user.

Make sure you have a reasonable rolling scheme for the logs of some way to archive them.

Also will the developers be able to access these logs? How? Will users "email" the logs? If so make sure they are a reasonable size that can be emailed.

Title: Should client side have a log?

Body:
The client side of my application is written in VB.Net, it accesses a java server.
Server logs every request that was made by client, client shows every exception to the user (with an option to send it to support).

The question is: would you add logs to the client side?
If yes, what information does it make sense to write to the client log?


问:
What are the ways to avoid duplication of logic between domain classes and SQL queries?
The example below is totally artificial and its only purpose is to get my point across.

Suppose I have an SQL table:

```<code>CREATE TABLE rectangles (
  width int,
  height int
);
</code>```

Domain class:

```<code>public class Rectangle {
  private int width;
  private int height;

  /* My business logic */
  public int area() {
    return width * height;
  }
}
</code>```

Now suppose that I have a requirement to show to the user the total area of all rectangles in the database.
I can do that by fetching all the rows of the table, turning them to objects and iterating over them.
But this looks just stupid, because I have lots and lots of rectangles in my table.

So I do this:

```<code>SELECT sum(r.width * r.height)
FROM rectangles r
</code>```

This is easy, fast and uses the strengths of the database.
However, it introduces duplicated logic, because I have the same calculation in my domain class also.

Of course, for this example the duplication of logic is not fatal at all.
However, I face the same problem with my other domain classes, which are more complex.

答:
As lxrec pointed out, it'll vary from codebase to codebase. Some applications will allow you to put those kind of business logic into SQL Functions and/or queries and allow you to run those anytime you need to show those values to the user.

Sometimes it may seem stupid, but it's better to code for correctness than performance as a primary objective.

In your sample, if you're showing the value of the area for a user in a webform, you'd have to:

```<code>1) Do a post/get to the server with the values of x and y;
2) The server would have to create a query to the DB Server to run the calculations;
3) The DB server would make the calculations and return;
4) The webserver would return the POST or GET to the user;
5) Final result shown.
</code>```

It's stupid for simple things like the one on the sample, but it may be necessary to more complex stuff like calculating the IRR of an investment of a client in a banking system.

Code for correctness. If your software is correct, but slow, you'll have chances to optimize where you need (after profiling). If that means keeping some of the business logic in the database, so be it. That's why we have refactoring techniques.

If it becomes slow, or unresponsive, than you may have some optimizations to do, like violating the DRY principle, which is not a sin if you surround yourself of the proper unit testing and consistency testing.

Body:
As lxrec pointed out, it'll vary from codebase to codebase. Some applications will allow you to put those kind of business logic into SQL Functions and/or queries and allow you to run those anytime you need to show those values to the user.

Sometimes it may seem stupid, but it's better to code for correctness than performance as a primary objective.

In your sample, if you're showing the value of the area for a user in a webform, you'd have to:

1) Do a post/get to the server with the values of x and y;
2) The server would have to create a query to the DB Server to run the calculations;
3) The DB server would make the calculations and return;
4) The webserver would return the POST or GET to the user;
5) Final result shown.

It's stupid for simple things like the one on the sample, but it may be necessary to more complex stuff like calculating the IRR of an investment of a client in a banking system.

Code for correctness. If your software is correct, but slow, you'll have chances to optimize where you need (after profiling). If that means keeping some of the business logic in the database, so be it. That's why we have refactoring techniques.

If it becomes slow, or unresponsive, than you may have some optimizations to do, like violating the DRY principle, which is not a sin if you surround yourself of the proper unit testing and consistency testing.


问:
TEA algorithm constant 0x9e3779b9 said to be derived from golden ratio, but the golden number is 1.618?
I'm trying to understand a constant 0x9e3779b9.

What kind of data is this? It's not binary, not decimal, what is this?

It's a constant used on the TEA algorithm.
It says it's derived from the golden number,
but the golden number is 1.618?

答:
As others pointed out here and on https://stackoverflow.com/questions/4948780/magic-numbers-in-boosthash-combine, the number is indeed constructed from the golden ratio.

But there is another important reason why numbers such as pi, phi or e are used in cryptographic functions. Of course, in principle, any "reasonably random" bit sequence could be used as a constant. But it puts the creator of the function under suspicion of having engineered the value, e.g. in order to create a particular weakness in the algorithm (known only to him) that he can then exploit when you use his function.

By constructing the value from well-known "natural" constants, this kind of suspicion can be averted to some degree.


问:
Avoid branch conflicts/race conditions with task branches
Background

Support and Sprint are the test branches for bugs and tasks

Each bug gets a new branch from master, which is merged into Support, when tested good, a pull request is made between the Support branch and master.

Each task gets a new branch from master, which is merged into Sprint, when tested good, a pull request is made between the Sprint branch and master

Allows for any given bug fix to go live at a moments notice when tested good, and allows for any given task to go live as and when its ready.

Allows for any part of a task to be tested in isolation

Allows for any bug to be tested in isolation

Problem

If Task 123 and Task 234 both change method DoSomethingToX, this creates a conflict in Sprint which must be resolved. This will break one or both, or neither of the tasks. The fix will be made as part of the merge (because its resolving a conflict), so will be committed to Sprint, not Task 123/234.

I do not want to merge Sprint back into a task, because that will then merge all other In Progress tasks into that task, and could potentially put those task-parts live

How would i better manage these conflicts?

Is this  what cherry-pick is for?

Is there a way to go with this type of architecture and avoid these conflicts?

Are there a set of coding standards that would help avoid these conflicts?

(Support and Sprint are only there to give a branch to create deployment builds from for testing, this is already pretty finely ingrained into the entire process and is unlikely to be changed)

答:
I don't see any process to merge the RC or Master branches back into the working branches (Bug###, Task###, etc).

This is fine, as long as each Bug/Task make minor changes to Support/Sprint branches and are not affected by the other ones.

You want branch drift to be low. You don't want to merge other changes into the task/bug branches, which means these  branches are going to by definition drift from their targets.

If multiple features that are being worked on simultaneously are changing the same method so meaningfully you have problems that also suggests either:

The method is too complicated/large

Your features should be developed in sequence

You can also work to make your tasks smaller so they are easier to finish quickly. This is more important if you are unable to merge upstream changes. Or have some sort of communication between your teams to know when they should pull these changes (standups? or something?).

I do not want to merge Sprint back into a task, because that will then merge all other In Progress tasks into that task, and could potentially put those task-parts live

This will also mean you are delaying any problems resulting from other tasks. For example, consider Task1 and Task2 both modify similar code. Task1 is committed/tested/pushed to the Sprint branch but Task2 takes another five days. Because you are never pulling the updated Task2 code and rebasing to it, when you push Task1 you are now running the risk of breaking your Sprint.

How would i better manage these conflicts?

Rebase your commit from Task2 onto the current Sprint branch, before pushing to Sprint.


问:
Developers blocked by waiting on code to merge from another branch using GitFlow
Our team just made the switch from FogBugz & Kiln/Mercurial to Jira & Stash/Git. We are using the Git Flow model for branching, adding subtask branches off of feature branches (relating to Jira subtasks of Jira features). We are using Stash to assign a reviewer when we create a pull request to merge back into the parent branch (usually develop but for subtasks back into the feature branch).

The problem we're finding is that even with the best planning and breakdown of feature cases, when multiple developers are working together on the same feature, say on the front-end and back-end, if they are working on interdependent code that is in separate branches one developer ends up blocking the other.

We've tried pulling between each others' branches as we develop. We've also tried creating local integration branches each developer can pull from multiple branches to test the integration as they develop. Finally, and this seems to work possibly the best for us so far, though with a bit more overhead, we have tried creating an integration branch off of the feature branch right off the bat. When a subtask branch (off of the feature branch) is ready for a pull request and code review, we also manually merge those change sets into this feature integration branch. Then all interested developers are able to pull from that integration branch into other dependent subtask branches. This prevents anyone from waiting for any branch they are dependent upon to pass code review.

I know this isn't necessarily a Git issue - it has to do with working on interdependent code in multiple branches, mixed with our own work process and culture. If we didn't have the strict code-review policy for develop (true integration branch) then developer 1 could merge to develop for developer 2 to pull from. Another complication is that we are also required to do some preliminary testing as part of the code review process before handing the feature off to QA.This means that even if front-end developer 1 is pulling directly from back-end developer 2's branch as they go, if back-end developer 2 finishes and his/her pull request is sitting in code review for a week, then front-end developer 2 technically can't create his pull request/code review because his/her code reviewer can't test because back-end developer 2's code hasn't been merged into develop yet.

Bottom line is we're finding ourselves in a much more serial rather than parallel approach in these instance, depending on which route we go, and would like to find a process to use to avoid this.

Last thing I'll mention is we realize by sharing code across branches that haven't been code reviewed and finalized yet we are in essence using the beta code of others. To a certain extent I don't think we can avoid that and are willing to accept that to a degree.

答:
Your problem: Developer A branches from Master, developer B branches from Master, both work on closely related features, and the inevitable fact that the merges into the Master branch are difficult because of inevitable conflicts is what holds everyone back. </p>

<p>If this is foreseeable, then A and B could first create a common branch, then each branch for their separate work from this common branch, merge each of their separate work into the common branch, and now you have a conflict free branch that is much easier to integrate. </p>

Body:
Your problem: Developer A branches from Master, developer B branches from Master, both work on closely related features, and the inevitable fact that the merges into the Master branch are difficult because of inevitable conflicts is what holds everyone back.

If this is foreseeable, then A and B could first create a common branch, then each branch for their separate work from this common branch, merge each of their separate work into the common branch, and now you have a conflict free branch that is much easier to integrate.


问:
Common mistakes with javascript arithmetic
I've ran into several oddities using javascripts floating point arithmetic, but I can never recall them off the top of my head!

What are some common mistakes when using JavaScript to do math?

答:
The common problems with javascript arithmetic relate to the use of parseInt, or the lack of.

Not using radix when converting strings to integers:

```<code>parseInt("0137"); // 95!
parseInt("0137", 10); // 137
</code>```

Not using parseInt at all with arithmetic:

```<code>var a = "2";
alert(a + 5); // 25
alert(a - 5): // -3!
</code>```

Misunderstanding floating point arithmetic (applies to all languages, not just JS):

```<code>alert(23 * 1.40 == 32.2); // false, 23 * 1.40 is represented as 32.199999999
alert((23 * 1.40).toFixed(1) == 32.2); // true
</code>```

Calculating currency with floating points may lead to rounding errors, currency values should be treated as integers (multiplied with 100) before processing.

ContentLicense: CC BY-SA 2.5

Body:
The common problems with javascript arithmetic relate to the use of parseInt, or the lack of.

Not using radix when converting strings to integers:

parseInt("0137"); // 95!
parseInt("0137", 10); // 137

Not using parseInt at all with arithmetic:

var a = "2";
alert(a + 5); // 25
alert(a - 5): // -3!

Misunderstanding floating point arithmetic (applies to all languages, not just JS):

alert(23 * 1.40 == 32.2); // false, 23 * 1.40 is represented as 32.199999999
alert((23 * 1.40).toFixed(1) == 32.2); // true

Calculating currency with floating points may lead to rounding errors, currency values should be treated as integers (multiplied with 100) before processing.


问:
How to handle mismatched request body and content-type header?
If someone makes a request with a Content-Type that doesn't match the syntax of the request body, how should the server respond? Is there a standard way of handling this (seems like there would be), or is it up to the discretion of the service implementor?

EG Someone posts something with Content-Type 'application/json', but the post body has urlencoded syntax.  How should this be handled?

答:
You should respond with HTTP 400: Bad Request.

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

The response body should include an explanation of why the request was rejected—e.g., “Invalid JSON”.


答:
I've written a silly example to explain an idea:

```<code>class BinaryIntegerOperation
{
    public int Execute(string operation, int operand1, int operand2)
    {
        var split = operation.Split(':');
        var opCode = split[0];
        if (opCode == "MULTIPLY")
        {
            var args = split[1].Split(',');
            var result = IsFirstOperand(args[0]) ? operand1 : operand2;
            for (var i = 1; i < args.Length; i++)
            {
                result *= IsFirstOperand(args[i]) ? operand1 : operand2;
            }
            return result;
        }
        else
        {
            throw new NotImplementedException();
        }
    }
    public string ToSqlExpression(string operation, string operand1Name, string operand2Name)
    {
        var split = operation.Split(':');
        var opCode = split[0];
        if (opCode == "MULTIPLY")
        {
            return string.Join("*", split[1].Split(',').Select(a => IsFirstOperand(a) ? operand1Name : operand2Name));
        }
        else
        {
            throw new NotImplementedException();
        }
    }
    private bool IsFirstOperand(string code)
    {
        return code == "0";
    }
}
</code>```

So, if you have some logic:

```<code>var logic = "MULTIPLY:0,1";
</code>```

You can re-use it in domain classes:

```<code>var op = new BinaryIntegerOperation();
Console.WriteLine(op.Execute(logic, 3, 6));
</code>```

Or in your sql-generation layer:

```<code>Console.WriteLine(op.ToSqlExpression(logic, "r.width", "r.height"));
</code>```

And, of course, you can change it easily. Try this:

```<code>logic = "MULTIPLY:0,1,1,1";
</code>```

Title: What are the ways to avoid duplication of logic between domain classes and SQL queries?

Body:
The example below is totally artificial and its only purpose is to get my point across.

Suppose I have an SQL table:

```<code>CREATE TABLE rectangles (
  width int,
  height int
);
</code>```

Domain class:

```<code>public class Rectangle {
  private int width;
  private int height;

  /* My business logic */
  public int area() {
    return width * height;
  }
}
</code>```

Now suppose that I have a requirement to show to the user the total area of all rectangles in the database.
I can do that by fetching all the rows of the table, turning them to objects and iterating over them.
But this looks just stupid, because I have lots and lots of rectangles in my table.

So I do this:

```<code>SELECT sum(r.width * r.height)
FROM rectangles r
</code>```

This is easy, fast and uses the strengths of the database.
However, it introduces duplicated logic, because I have the same calculation in my domain class also.

Of course, for this example the duplication of logic is not fatal at all.
However, I face the same problem with my other domain classes, which are more complex.

Body:
I've written a silly example to explain an idea:

class BinaryIntegerOperation
{
    public int Execute(string operation, int operand1, int operand2)
    {
        var split = operation.Split(':');
        var opCode = split[0];
        if (opCode == "MULTIPLY")
        {
            var args = split[1].Split(',');
            var result = IsFirstOperand(args[0]) ? operand1 : operand2;
            for (var i = 1; i < args.Length; i++)
            {
                result *= IsFirstOperand(args[i]) ? operand1 : operand2;
            }
            return result;
        }
        else
        {
            throw new NotImplementedException();
        }
    }
    public string ToSqlExpression(string operation, string operand1Name, string operand2Name)
    {
        var split = operation.Split(':');
        var opCode = split[0];
        if (opCode == "MULTIPLY")
        {
            return string.Join("*", split[1].Split(',').Select(a => IsFirstOperand(a) ? operand1Name : operand2Name));
        }
        else
        {
            throw new NotImplementedException();
        }
    }
    private bool IsFirstOperand(string code)
    {
        return code == "0";
    }
}

So, if you have some logic:

var logic = "MULTIPLY:0,1";

You can re-use it in domain classes:

var op = new BinaryIntegerOperation();
Console.WriteLine(op.Execute(logic, 3, 6));

Or in your sql-generation layer:

Console.WriteLine(op.ToSqlExpression(logic, "r.width", "r.height"));

And, of course, you can change it easily. Try this:

logic = "MULTIPLY:0,1,1,1";


答:
Empty interfaces are generally consider bad practice

I disagree. Read about marker interfaces.

Whereas a typical interface specifies functionality (in the form of
  method declarations) that an implementing class must support, a marker
  interface need not do so. The mere presence of such an interface
  indicates specific behavior on the part of the implementing class.


问:
Is cyclomatic complexity density a good software quality metric?
Where I define Cyclomatic complexity density as:

```<code>Cyclomatic complexity density = Cyclomatic complexity / Lines of code
</code>```

I was reading previous discussions about cyclomatic complexity and there seems to be a sort of consensus that it has mixed usefulness, and as such there probably isn't a strong motive for using it over a simple lines of code (LOC) metric. I.e. As the size of a class or method increases beyond some threshold the probability of defects and of there having been poor design choices goes up.

It seems to me that cyclomatic complexity (CC) and LOC will tend to be correlated, hence the argument for use of the simpler LOC metric. However, there may be outlier cases where complexity is higher within some region of code, i.e. there is a higher density of execution branches in some pieces code (compared to the average) and I'm wondering if that will tend to be correlated with the presence of defects.

Is there any evidence for or against, or are there any experiences around the use of such a complexity density metric?

Or perhaps a better metric is to have both a LOC and a CC threshold, and we consider passing either threshold as bad.

答:
There are no software quality metrics that are good - at least none are known yet. Years of research hasn't provided us with any good one yet.

So the answer whether any of your suggested metrics is a good metric for software quality is a disappointing "no."

There are some metrics that are reasonable indicators of bad software. But the lack of signs of bad software doesn't make software good. Besides, those indicators are very fussy with lots of exceptions, so automatic refusal of bad code is impractical in practice.

Researchers debate those metrics and correlate the metrics with bugs, but usually those correlations are no stronger than "larger programs contain more bugs." As this entry on Wikipedia admits:

The essence of this observation is that larger programs (more complex programs as defined by McCabe's metric) tend to have more defects. Although this relation is probably true, it isn't commercially useful.

As a result, those metrics are barely used in the commercial world - they don't save time nor money.

This should not stop researchers from looking for better ones. But so far, in my opinion it's a theoretical exercise with barely any practical usage.

During my 20 years of working in the commercial ICT, I've encountered two metrics used in practice, and neither can be automated:

"Number of paying customers satisfied," also known as "How much does it earn us?"

"WTFs per minute" when peers are reading your code.

Which is why this image is popular - I've seen it in multiple shops:


问:
Multiple different versions of similar apps in one project
I need some help to improve the architecture of a site I've built. What I want to achieve within a single Django project is the following:

I want a site that comes in several versions (one per year), such that each version has a set of apps that are related to that version.

I want to keep all the old versions of the site and the state of the apps in that version, but still being able to add/change/remove the apps for any other version. That is, the apps may be different across versions (models, methods, admin, templates, anything basically).

I want each app that belongs to a version to have the data for that version only. App1 on version 2012 should have one database table, and App1 on version 2013 should have another, even if they are the same.

It could look something like this:

```<code>site.com/2012
    App1_v1
    App2_v1

site.com/2013
    App1_v1
    App2_v2 (maybe added some fields or methods, changed templates)

site.com/2014
    App1_v2
    App2_v2
    App3_v1
</code>```

My current solution is rather horrible. When a new version of the site is launched, I simply copy-paste an earlier app and have the old app be as it is, and then adding/modifying the new version of the app. But, as I add more apps and more versions come, I get a stupid amount of apps and it feels like bad design.

How can I achieve this in Django in a better way? Or at least, how can I design/structure it in a better way?
I think about having some base model for each app, from which each version then inherits from, but that still makes a lot of apps.

As an example of an app I have, it may look like this:

App name: App_v1_2012

Model

```<code>class Bag(models.Model)
    name = models.CharField()

class Item(models.Model)
    name = models.CharField()
    in_bag = models.ForeignKey(Bag)
</code>```

View

```<code>class IndexView(generic.ListView):
    model = Bag
    template_name = 'sometemplate_2012.html'
</code>```

App name: App_v1_2013

Model

```<code>class Bag(models.Model)
    name = models.CharField()

class Item(models.Model)
    name = models.CharField()
    in_bag = models.ForeignKey(Bag)
</code>```

View

```<code>class IndexView(generic.ListView):
    model = Bag
    template_name = 'sometemplate_2013.html'
</code>```

App name: App_v2_2014

Model

```<code>class Bag(models.Model)
    bag_name = models.CharField()
    owner = models.ForeignKey(User)

class Item(models.Model)
    name = models.CharField()
    in_bag = models.ForeignKey(Bag)
</code>```

View

```<code>class IndexView(generic.ListView):
    model = Bag
    template_name = 'sometemplate_2014.html'
</code>```

As you can see, my biggest problem is the violation of the DRY principle. Everything get copy-pasted, but it's the same information.

答:
I may be misunderstanding some details of your question, but I'll try anyway. This is how I would do it:

I would structure App1, App2, etc... as Python packages, and would version these packages to map to App1_v1, App1_v2, App2_v1, etc...

I would then create another package for site.com, and version it to map to site.com/2012, site.com/2013, etc...

All of these packages would be in separate source repositories.

The different versions of the site.com package would depend on the App1_vX, App2_vX packages, at the appropriate versions.

I would then deploy the different versions of site.com to different servers, or at least different virtual environments, as you can't install multiple versions of the same app in the same environment.

I think that would be the cleanest solution.