问:
Should copyright notice appear on new additions with MIT Licence?
If a library licensed under MIT licence is copied and extended on, should new additions contain the copyright notice as well?

Considering that the additions may at some point overwhelm the initial library, could the initial MIT licence ever change to some other licence?

答:
New additions to an MIT-licensed library don't preclude the inclusion of any additional copyright holders.  So yes, you should include the new copyright declarations.

The MIT license is included in any derivative works.  So if you use the library in your application, and your application has its own license, you still have to include the MIT license (and any copyright additions) in your work.

It's hard to imagine this getting too onerous.  The folks making contributions to the library and holding the copyrights to those contributions deserved to be acknowledged, and having so many contributors to a library that the copyrights might actually consume a whole page of text is a good problem, not a bad one.

Xamarin (the company behind Mono) solves this problem (and some others) by requiring contributors to assign their copyright to Xamarin.


答:
The MIT license only requires that the copyright notice is kept. It does not require you to keep the same license. And this makes sense: The MIT license wants you to do with the code whatever you want, but if you build upon the source code, it will still contain parts that were written by the original author(s). These authors retain the copyright for the parts they wrote, although they licensed the code to you under the MIT license.

A practical example: We have the following file:

```<code>/* Copyright (c) 2015 amon
 *
 * Permission is hereby granted
 * ...
 */

 A;
 B;
</code>```

You now extend the program with new functionality by adding a step C. You hold the copyright for these changes. It would usually look like this:

```<code>/* Copyright (c) 2015 Trodder
 * Copyright (c) 2015 amon
 *
 * Permission is hereby granted
 * ...
 */

 A;
 B;
 C;
</code>```

Since the MIT license allows you to sublicense the code, you can add your own license, but must keep the original copyright notice and original permission notice. I'd do it like this:

```<code>/* Copyright (c) 2015 Trodder
 * Copyright (c) 2015 amon
 *
 * You may use this code under the terms of the Wonderful-Trodder-Free-License (WTF-L)
 * ...
 *
 * This code builds upon previous effort by amon,
 * and is used under the following license:
 *
 * Permission is hereby granted
 * ...
 */

 A;
 B;
 C;
</code>```

Technically, you hold the copyright over your changes even when you do not write a “Copyright <year> <name>” line. However, this makes it confusing for readers of that code to understand who currently holds the copyright over what parts of the file.

ContentLicense: CC BY-SA 3.0

Title: Should copyright notice appear on new additions with MIT Licence?

Body:
If a library licensed under MIT licence is copied and extended on, should new additions contain the copyright notice as well?

Considering that the additions may at some point overwhelm the initial library, could the initial MIT licence ever change to some other licence?

Body:
The MIT license only requires that the copyright notice is kept. It does not require you to keep the same license. And this makes sense: The MIT license wants you to do with the code whatever you want, but if you build upon the source code, it will still contain parts that were written by the original author(s). These authors retain the copyright for the parts they wrote, although they licensed the code to you under the MIT license.

A practical example: We have the following file:

/* Copyright (c) 2015 amon
 *
 * Permission is hereby granted
 * ...
 */

 A;
 B;

You now extend the program with new functionality by adding a step C. You hold the copyright for these changes. It would usually look like this:

/* Copyright (c) 2015 Trodder
 * Copyright (c) 2015 amon
 *
 * Permission is hereby granted
 * ...
 */

 A;
 B;
 C;

Since the MIT license allows you to sublicense the code, you can add your own license, but must keep the original copyright notice and original permission notice. I'd do it like this:

/* Copyright (c) 2015 Trodder
 * Copyright (c) 2015 amon
 *
 * You may use this code under the terms of the Wonderful-Trodder-Free-License (WTF-L)
 * ...
 *
 * This code builds upon previous effort by amon,
 * and is used under the following license:
 *
 * Permission is hereby granted
 * ...
 */

 A;
 B;
 C;

Technically, you hold the copyright over your changes even when you do not write a “Copyright <year> <name>” line. However, this makes it confusing for readers of that code to understand who currently holds the copyright over what parts of the file.


问:
What's a reasonable limit for email confirmation re-sends?
I want a secure web app, and allowing infinite email confirmations and re-sends seems insecure. I was thinking 3 but would love an opinion from someone with experience.

Edit

Sending email with Postmark and don't want an attacker to burn through unlimited email credits. I also don't want to spam my users if an attacker were to send a bunch of emails.

That said, I don't want well-meaning users to not be able to re-send a confirmation. I was hoping someone would say "we use x number but upped it to x number and have had no more complaints.

Or maybe limiting this is stupid, for some other reason. I don't know.

答:
One should only resend once there is proof of delivery failure.

Some email providers use a period of time to attempt to deliver the email.  A typical the default is 48 hours.  Over this 48 hour period they may attempt to deliver the email N number of times, where N could be 8, 10, etc.

This is done to help on transient email errors.  For example, what if the person's inbox is full or thier service provider went down.  All of these return specific errors, for example the SMTP service call will return a 422 if the mail box is full.  A person could delete some of the mail and then that message would go through in that case on a subsequent attempt.

For a list of all codes, please see here:

http://www.serversmtp.com/en/smtp-error

For these types of errors, the provider would retry the message (automatically) again at a later period. Some returns are fatal, others may be classified as transient which may clear up after a period of time.

Finally after a period of time (say 48 hours) if the email is still not sent, they would report a delivery failure.  At that point, the delivery is considered a failure and manual intervention would be required.

Only then would one want to attempt another confirmation or perhaps contact the user to see if the errors can be corrected.

The web application you are designing should take those factors into account when sending email.


问:
Should one use Dependency Injection even if the class is used only once?
During a code review I have started having a bit of a dilemma as to whether use dependency injection or not. I would like to hear your thoughts, because this is kind of an ongoing theme and would help in the future code reviews as well.

Before I start I want to say that from my knowledge DI is mostly used for dependency management and better, much easier unit testing (correct me if I am wrong please).

Now here is the scenario:

This is the class that will be used as a dependency only once and probably for good. Meaning it will stay that way for a while and no other class will be using it.

Reason being is because it is a refactoring of some legacy code and there was not much to be done but to separate it into another class, at least as a first good step, for following the SRP.

Also, another thing is that the hypothetical doSomethingImportant() hits the database.

```<code>public SomeClass
{
   public Object doSomethingImportant()
   {
      ...
   }
}
</code>```

Based on that information do you think it is okay to new up the dependency in the other class as opposed to using DI since:

Dependency management argument kind of falls off since it is only going to be used once.

&

Unit testing also falls off since I would rather do an integration or acceptance test to see how the method is interacting with the database in a real-life application.

```<code>public SomeOtherClass
{
   private readonly SomeClass _someClass = new SomeClass();

   public Object doSomethingImportantUsingDependency()
   {
      ...
   }
}
</code>```

I was personally inclined towards doing DI because it is considered good practice, but for a second there it felt like I was blindingly following the rules and not thinking it over since there are always exceptions to the rule.

What are your thoughts on this? I would love to hear.

PS: I don't think this is a generic "when should I use DI" question because it is very specific to this particular situation when unit tests are of no use and the class is going to be used only once so there is no need to centralize it for dependency management (even though it is good practice in general).

答:
If you do not apply DI as long as you do not really need it (not even for unit testing), nothing bad will happen. The code does not become error prone, "overly complicated", or hard to maintain. And if you decide to refactor the dependency out later, it will most probably not be much more effort than doing it now. That's a case where the YAGNI principle applies.

However, what you should check is if you are sure you really do not want to be able to unit test SomeOtherClass in isolation from SomeClass, and if the imposed dependency on the assemblies where SomeOtherClass and SomeClass live will not become a problem. If you are 100% sure that the answer to the former questions is "yes", then you can ignore DI.


问:
No exceptions C++ and partially constructed objects
Looking over Joint Strike Fighter Air Vehicle C++ Coding Standard, rule AV 73 states something on the lines: Default c++ constructors should be avoided if that means leaving object in a partially constructed place. This is obvious a good advice but things get complicated when you also disallow exceptions (as it does)

I wonder if they also try to give something else in return to make it practical. E.g. following example needs 2 faze construction if OUT_OF_MEMORY has to be handled (but the problem is more general of course)

```<code>class A {
    A() = default; // no way to report construction of B and C
    int Init(); // allocation failure of B/C can be reported only here
    private:
    B* b;
    C* c
}
</code>```

One way to handle the problem is to have a A* Create() static member but in this case A has to free store allocated or keep an non-fully initialized state inside A and check it inside every member access, which seems not better at all than using a C style

```<code>int Initialize(A& out) // stack allocation
int Initialize(unique_ptr<A>& out) // free store allocation
</code>```

EDIT I posted one possible approach bellow also. I took under consideration that dynamic memory allocation is necessary and the fact that any errors can happen while fully constructing an object. This is a scenario that is plausible for any driver development work.

答:
One way to handle these is to have factory functions:

```<code>expected<Missile> Missile::Create(Params...)
expected<unique_ptr<Missile>> Missile::Create(Params...)

class Missile {
  private:
   Missile() = default;
   int Initialize(int power) // second phase constructor {
     // other operations (besides out_of_memory) that may fail
     // can be reported from this function
     expected<PowerSupply> expectedPower = PowerSupply::Create(power);
     if (!expectedPower.valid()) {
       return expectedPower.get_error();
     }
     this->power = std::move(expectedPower); // from now on power.valid() true
     return SUCCESS;

  public:
  static expected<Missile> Missile::Create(int p) {
    // 1. call default constructor first, this is automatic
    // storage so no fail
    // 2. Initialize called.
    // If failure - report expected<Missile>::from_error(Initialize_STATUS);
    Missile m;
    auto status = m.Initialize(p);
    if (status != 0) return expected<Missile>::from_error(status);
    return Missile; // implicit conversion from T to expected<T>
  }
  static expected<unique_ptr<Missile>> Missile::Create(int p) {
    // 1. use operator new to construct - may fail -> expected::from_error(OUT_OF_MEMMORY)
    // 2. call Initialize and possibly report second phase errors
  }

  private:
  int power;
  expected<PowerSupply> power;
}
</code>```

This is cleaner than using out parameters and a complex object is able (using 2 phases) to build  it's dependencies, be it as automatic variable or free store allocated.

Class expected  default constructor only allocates automatic storage for T.  One can create an initialized expected instance by assigning a T instance to expected<T>

Body:
One way to handle these is to have factory functions:

expected<Missile> Missile::Create(Params...)
expected<unique_ptr<Missile>> Missile::Create(Params...)

class Missile {
  private:
   Missile() = default;
   int Initialize(int power) // second phase constructor {
     // other operations (besides out_of_memory) that may fail
     // can be reported from this function
     expected<PowerSupply> expectedPower = PowerSupply::Create(power);
     if (!expectedPower.valid()) {
       return expectedPower.get_error();
     }
     this->power = std::move(expectedPower); // from now on power.valid() true
     return SUCCESS;

  public:
  static expected<Missile> Missile::Create(int p) {
    // 1. call default constructor first, this is automatic
    // storage so no fail
    // 2. Initialize called.
    // If failure - report expected<Missile>::from_error(Initialize_STATUS);
    Missile m;
    auto status = m.Initialize(p);
    if (status != 0) return expected<Missile>::from_error(status);
    return Missile; // implicit conversion from T to expected<T>
  }
  static expected<unique_ptr<Missile>> Missile::Create(int p) {
    // 1. use operator new to construct - may fail -> expected::from_error(OUT_OF_MEMMORY)
    // 2. call Initialize and possibly report second phase errors
  }

  private:
  int power;
  expected<PowerSupply> power;
}

This is cleaner than using out parameters and a complex object is able (using 2 phases) to build  it's dependencies, be it as automatic variable or free store allocated.

Class expected  default constructor only allocates automatic storage for T.  One can create an initialized expected instance by assigning a T instance to expected<T>


问:
Unit testing and reusing extracted class
Currently I have 3 service classes, they all have a similar pattern, and I need to make a 4th service class which amalgamates the functionality of the other three.

Current three classes

```<code>public class PersonService : IPersonService
{
    public PersonServiceResult CreatePerson(CreatePersonParams createPersonParams)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            // [code]

            unitOfWork.Commit();
            return new PersonServiceResult(...);
        }
    }
}

public class OrderService : IOrderService
{
    public OrderServiceResult CreateOrder(
        int personId,
        IEnumerable<PurchaseItem> items)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            // [code]

            unitOfWork.Commit();
            return new OrderServiceResult(...);
        }
    }
}

public class PaymentProcessingService : IPaymentProcessingService
{
    public PaymentResult ProcessPayment(int orderId, CreditCard creditCard)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            // [code]

            unitOfWork.Commit();
            return new PaymentResult(...);
        }
    }
}
</code>```

Now I have a need to use the behavior in all 3 of these classes into one unit-of-work, I still need the 3 other classes to exist for other dependecies in the project.

My first thought would be to extract a class for each one of the 3 services which takes a unit-of-work as an argument.

Extraction of behavior from current classes

```<code>public class PersonCreator
{
    public CreatePersonResult CreatePerson(
        IUnitOfWork unitOfWork,
        CreatePersonParams createPerson)
    {
        // [code]
    }
}

public class PersonService : IPersonService
{
    private readonly PersonCreator Creator = new PersonCreator();

    public PersonServiceResult CreatePerson(CreatePersonParams createPersonParams)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            var result = Creator.CreatePerson(unitOfWork, createPersonParams);

            unitOfWork.Commit();
            return new PersonServiceResult(result);
        }
    }
}
</code>```

Proposed new class using extracted behavior

```<code>public class QuickOrderService : IQuickOrderService
{
    private readonly PersonCreator PersonCreator = new PersonCreator();
    private readonly OrderCreator OrderCreator = new OrderCreator();
    private readonly PaymentProcessor PaymentProcessor = new PaymentProcessor();

    public QuickOrderResult CreateQuickOrder(
        CreatePersonParams createPersonParams,
        IEnumerable<PurchaseItem> items,
        CreditCard creditCard)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            var person = PersonCreator.CreatePerson(unitOfWork, createPersonParams);
            var order = OrderCreator.CreateOrder(unitOfWork, person.Id, items);
            var payment = PaymentProcessor.Process(unitOfWork, order.Id, creditCard);

            unitOfWork.Commit();

            return QuickOrderResult(...);
        }
    }
}
</code>```

This works fine, but I am concerned about testing this new class.

Questions about proposal

Duplicate the majority of the tests for the QuickOrderService class

Do not test this class as the majority of it is covered by other tests

Inject PersonCreator, OrderCreator, and PaymentProcessor into QuickOrderService
instead of instanciating them and just test that QuickOrderService calls the dependencies correctly

Though when doing this whole excersise it makes me think there may be a better solution that reduces duplication while retains code coverage.

答:
Inject the three Creator-classes and test the calls to them by unittesting the QuickOrderService. This keeps the tests on the relevant classes.

Also, you might not need to haul the unitOfWork around. The implementation of Create could be changed to simply create a new transaction if none exists and otherwise return the existing transaction. This could keep track of the amount of calls to Create and Commit and only commit the transaction when the 'last' transaction that was requested is committed. Right now you have three services that take a unitOfWork and one that doesn't. Strive for consistency in your project and either pass ALL the services a unitOfWork or have the service manage a unitOfWork for itself.


问:
Software Design Idea for multi tier architecture
I am currently investigating multi tier architecture design for a web based application in MVC3. I already have an architecture but not sure if its the best I can do in terms of extendability and performance.

The current architecure has following components

DataTier (Contains EF POCO objects)

DomainModel (Contains Domain related objects)

Global (Among other common things it contains Repository objects for CRUD to DB)

Business Layer (Business Logic and Interaction between Data and Client and CRUD using repository)

Web(Client) (which talks to DomainModel and Business but also have its own ViewModels for Create and Edit Views for e.g.)

Note: I am using ValueInjector for convering one type of entity to another. (which is proving an overhead in this desing. I really dont like over doing this.)

My question is am I having too many tiers in the above architecure?
Do I really need domain model? (I think I do when I exposes my Business Logic via WCF to external clients).

What is happening is that for a simple database insert it

(1) create ViewModel

(2) Convert ViewModel to DomainModel for Business to understand

(3) Business Convert it to DataModel for Repository and then data comes back in the same order.

Few things to consider,

I am not looking for a perfect architecure solution as it does not exits.
I am looking for something that is scalable.
It should resuable (for e.g. using design patterns ,interfaces, inheritance etc.)
Each Layers should be easily testable.

Any suggestions or comments is much appriciated.

Thanks,

答:
The default approach should be three "layers" or modules (Data Access, Business, UI). If you have any less, or any more, you better have a darn good reason IMO as three layers is the best solution for 90%+ of enterprise projects. More layers means fixes and changes take more time. Less layers can cause confusion and resistance to change as well.

Why I used "layers" in quotes is that mandating that the business layer sits between data access and the UI tightly couples your business logic to your database. For example, what if the user wants to mess with hypothetical situations with your widget instead of getting information about the widget which he owns? This is an operation which requires no data access. The easiest way to do this is New Widget -> Populate Widget from UI -> Call Widget.GetInfo() -> display info.

What if a job wants to access records but does not need business logic? Business and data access should be separate, but I would not say that business sits on top of data access.

OwnerDisplayName: activebiz


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
For a long time I argued that they were of equal worth, or so very close to equal that the possible gain by making the right choice was far, far, below the cost of arguing about it.

Being consistent is important, though. So I said let's flip a coin and get on to writing code.

I've seen programmers resist change like this before. Get over it! I've switched many times in my career. I even use different styles in my C# than in my PowerShell.

A few years ago I was working on a team (~20 developers) that decided to ask for input, and then make a decision, and then enforce that across all the code base. We'd have 1 week to decide.

Lots of groans & eye-rolling. Lots of "I like my way, because it's better" but no substance.

As we were studying the finer points of the question, someone asked how to deal with this issue in brace-on-the-same-line style:

```<code>void MyFunction(
    int parameterOne,
    int parameterTwo) {
    int localOne,
    int localTwo
}
</code>```

Note that it's not immediately obvious where the parameter list ends, and the body begins. Compare to:

```<code>void MyFunction(
    int parameterOne,
    int parameterTwo)
{
    int localOne,
    int localTwo
}
</code>```

We did some reading on how folks around the world had dealt with this problem, and found the pattern of adding a blank line after the open brace:

```<code>void MyFunction(
    int parameterOne,
    int parameterTwo) {

    int localOne,
    int localTwo
}
</code>```

If you're going to make a visual break, you may as well do it with a brace. Then your visual breaks become consistent, too.

Edit: Two alternatives to the 'extra blank line' solution when using K&R:

1/ Indent the function arguments differently from the function body

2/ Put the first argument on the same line as the function name and align further arguments on new lines to that first argument

Examples:

1/

```<code>void MyFunction(
        int parameterOne,
        int parameterTwo) {
    int localOne,
    int localTwo
}
</code>```

2/

```<code>void MyFunction(int parameterOne,
                int parameterTwo) {
    int localOne,
    int localTwo
}
</code>```

/Edit

I still argue that consistency is more important than other considerations, but if we don't have an established precedent, then brace-on-next-line is the way to go.

Body:
For a long time I argued that they were of equal worth, or so very close to equal that the possible gain by making the right choice was far, far, below the cost of arguing about it.

Being consistent is important, though. So I said let's flip a coin and get on to writing code.

I've seen programmers resist change like this before. Get over it! I've switched many times in my career. I even use different styles in my C# than in my PowerShell.

A few years ago I was working on a team (~20 developers) that decided to ask for input, and then make a decision, and then enforce that across all the code base. We'd have 1 week to decide.

Lots of groans & eye-rolling. Lots of "I like my way, because it's better" but no substance.

As we were studying the finer points of the question, someone asked how to deal with this issue in brace-on-the-same-line style:

void MyFunction(
    int parameterOne,
    int parameterTwo) {
    int localOne,
    int localTwo
}

Note that it's not immediately obvious where the parameter list ends, and the body begins. Compare to:

void MyFunction(
    int parameterOne,
    int parameterTwo)
{
    int localOne,
    int localTwo
}

We did some reading on how folks around the world had dealt with this problem, and found the pattern of adding a blank line after the open brace:

void MyFunction(
    int parameterOne,
    int parameterTwo) {

    int localOne,
    int localTwo
}

If you're going to make a visual break, you may as well do it with a brace. Then your visual breaks become consistent, too.

Edit: Two alternatives to the 'extra blank line' solution when using K&R:

1/ Indent the function arguments differently from the function body

2/ Put the first argument on the same line as the function name and align further arguments on new lines to that first argument

Examples:

1/

void MyFunction(
        int parameterOne,
        int parameterTwo) {
    int localOne,
    int localTwo
}

2/

void MyFunction(int parameterOne,
                int parameterTwo) {
    int localOne,
    int localTwo
}

/Edit

I still argue that consistency is more important than other considerations, but if we don't have an established precedent, then brace-on-next-line is the way to go.


答:
I would start with eliminating the duplicated code first by building a generic creation service, something along the lines of

```<code>   class GenericCreatorService<T>
   {
        UnitOfWorkFactory _unitOfWorkFactory;

        // ...

        public T Create(Func<T,UnitOfWork> func)
        {
           using (var unitOfWork = _unitOfWorkFactory.Create())
           {
                T result = func(unitOfWork);
                unitOfWork.Commit();
                return result;
           }
        }
   }
</code>```

Now you just need to unit-test that once. Reuse it to implement your original service classes, for example,

```<code>public class PersonService : IPersonService
{
    private readonly PersonCreator Creator = new PersonCreator();

    public PersonServiceResult CreatePerson(CreatePersonParams createPersonParams)
    {
        var gs = new GenericCreatorService<PersonServiceResult>(...);
        return gs.Create( uow => PersonCreator.CreatePerson(uow,createPersonParams))
    }
}
</code>```

You should focus on testing the individual Creator classes, one test for each, and its debatable if you really need to unit test the individual service classes any more, since they contain only some very simple orchestration code. If you feel you need an extra test for your QuickOrderService because the real implementation is more complicated, you can still do what @JDT suggested and use DI for the other creators.

Title: Unit testing and reusing extracted class

Body:
Currently I have 3 service classes, they all have a similar pattern, and I need to make a 4th service class which amalgamates the functionality of the other three.

Current three classes

```<code>public class PersonService : IPersonService
{
    public PersonServiceResult CreatePerson(CreatePersonParams createPersonParams)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            // [code]

            unitOfWork.Commit();
            return new PersonServiceResult(...);
        }
    }
}

public class OrderService : IOrderService
{
    public OrderServiceResult CreateOrder(
        int personId,
        IEnumerable<PurchaseItem> items)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            // [code]

            unitOfWork.Commit();
            return new OrderServiceResult(...);
        }
    }
}

public class PaymentProcessingService : IPaymentProcessingService
{
    public PaymentResult ProcessPayment(int orderId, CreditCard creditCard)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            // [code]

            unitOfWork.Commit();
            return new PaymentResult(...);
        }
    }
}
</code>```

Now I have a need to use the behavior in all 3 of these classes into one unit-of-work, I still need the 3 other classes to exist for other dependecies in the project.

My first thought would be to extract a class for each one of the 3 services which takes a unit-of-work as an argument.

Extraction of behavior from current classes

```<code>public class PersonCreator
{
    public CreatePersonResult CreatePerson(
        IUnitOfWork unitOfWork,
        CreatePersonParams createPerson)
    {
        // [code]
    }
}

public class PersonService : IPersonService
{
    private readonly PersonCreator Creator = new PersonCreator();

    public PersonServiceResult CreatePerson(CreatePersonParams createPersonParams)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            var result = Creator.CreatePerson(unitOfWork, createPersonParams);

            unitOfWork.Commit();
            return new PersonServiceResult(result);
        }
    }
}
</code>```

Proposed new class using extracted behavior

```<code>public class QuickOrderService : IQuickOrderService
{
    private readonly PersonCreator PersonCreator = new PersonCreator();
    private readonly OrderCreator OrderCreator = new OrderCreator();
    private readonly PaymentProcessor PaymentProcessor = new PaymentProcessor();

    public QuickOrderResult CreateQuickOrder(
        CreatePersonParams createPersonParams,
        IEnumerable<PurchaseItem> items,
        CreditCard creditCard)
    {
        using (var unitOfWork = _unitOfWorkFactory.Create())
        {
            var person = PersonCreator.CreatePerson(unitOfWork, createPersonParams);
            var order = OrderCreator.CreateOrder(unitOfWork, person.Id, items);
            var payment = PaymentProcessor.Process(unitOfWork, order.Id, creditCard);

            unitOfWork.Commit();

            return QuickOrderResult(...);
        }
    }
}
</code>```

This works fine, but I am concerned about testing this new class.

Questions about proposal

Duplicate the majority of the tests for the QuickOrderService class

Do not test this class as the majority of it is covered by other tests

Inject PersonCreator, OrderCreator, and PaymentProcessor into QuickOrderService
instead of instanciating them and just test that QuickOrderService calls the dependencies correctly

Though when doing this whole excersise it makes me think there may be a better solution that reduces duplication while retains code coverage.

Body:
I would start with eliminating the duplicated code first by building a generic creation service, something along the lines of

   class GenericCreatorService<T>
   {
        UnitOfWorkFactory _unitOfWorkFactory;

        // ...

        public T Create(Func<T,UnitOfWork> func)
        {
           using (var unitOfWork = _unitOfWorkFactory.Create())
           {
                T result = func(unitOfWork);
                unitOfWork.Commit();
                return result;
           }
        }
   }

Now you just need to unit-test that once. Reuse it to implement your original service classes, for example,

public class PersonService : IPersonService
{
    private readonly PersonCreator Creator = new PersonCreator();

    public PersonServiceResult CreatePerson(CreatePersonParams createPersonParams)
    {
        var gs = new GenericCreatorService<PersonServiceResult>(...);
        return gs.Create( uow => PersonCreator.CreatePerson(uow,createPersonParams))
    }
}

You should focus on testing the individual Creator classes, one test for each, and its debatable if you really need to unit test the individual service classes any more, since they contain only some very simple orchestration code. If you feel you need an extra test for your QuickOrderService because the real implementation is more complicated, you can still do what @JDT suggested and use DI for the other creators.


问:
Test Driven Development: A good/accepted way to test file system operations?
I am working on a project at the moment that generates a table (among other things) based on the contents of a file-system, and in turn does some meta-data modifications on the things it finds.  The question is: how should tests be written around this, or set up?  Is there an easy way to mock this out? Or should I setup a "sandbox"?</p>

答:
This is the kind of thing you definitely need to integration test, as real-world file systems have all kind of strange behavior (like the way Windows won't allow deleting a file if any process, including the deleter, has it open).

So the TDD approach is to write the integration test first (TDD, strictly speaking, doesn't have distinct concepts of 'unit test' and 'integration test'; they are just tests). Quite likely that will be enough; so job done, stop, go home.

If not, there will be some internal complexity that isn't easy to adequately test by arranging files. In which case, you simply take that complexity out, put it in a class, and write unit tests for that class. Quite likely you will find that that common class is usable in the database, xml file, etc. cases too.

In no case would you take the fundamental core of the code you are writing and 'mock' it out in order to write tests that will pass whether or not the unit under test is wrong.


问:
Handling DomainExceptions using REST endpoint
Suppose I'm doing some DDD.
Now, I have a microservice reflecting a bounded context/a part of a bounded context.

Now, suppose there is a REST endpoint:

```<code>'/somedomainmodel/someaction'
</code>```

My API user is doing a POST request with somehow invalid data.
I'm using Java and assume that following chain is executed:

request is handled by a Spring controller or something else

controller is invoking a method on an application service

application service is doing some action on a domain model

But as I mentioned before, data provided by an user is somehow incorrect and could cause my domain object to get into invalid state. So a subclass of DomainException extends RuntimeException is thrown.

Now: how should I handle this? Suppose my endpoint is used by a frontend and I want to display a proper message to user.

Should I return a status code and a message in a response?
Where should it be detected and how? In an application service? Or maybe in a controller? And since it's not a checked exception, how should I handle it? Try/Catch for a runtime exception seems to be awful.

Maybe if we're talking about specifing implementation, should I use something like spring's @ExceptionHandler?

答:
You should return a 4xx error with a detailed description of the reason the request failed in the response body.

Can't help with the Java implementation. In many Python frameworks you would throw a 4xx exception as soon as your code has determined that the HTTP request is going to fail and this is caught by the framework and returns a 4xx HTTP status message.


问:
How do you find out what resources are unmanaged?
Looking through the .NET documentation, specifically the WebRequest class, I don't see any information indicating that I should wrap an instantiation of it in a using statement. Even the provided example does not do this. In most examples online however, this is exactly what's done.

My question is then, how do I know specifically which classes need to be disposed? Is there a general rule of thumb or do you inspect class definitions to see if they somehow handle unmanaged resources?

答:
My question is then, how do I know specifically which classes need to be disposed?

Does it implement IDisposable? Yes? Then it needs to be disposed. If not, not. You can maybe get away without it in some apps (C# and modern operating systems in general are better about cleaning up after you), but it is still wrong®.

There are a very few framework classes that need Close (or something similar) called instead, and do not implement IDisposable, but these will say so in their documentation. These though are exceptions.


问:
Language compiled to JS – most elegant way to do synchronous-style waits
I'm trying to make (yet another) language that compiles to JavaScript. One of the features I'd like to have is the ability to perform JavaScript's async operations synchronously (not exactly synchronously – without blocking the main thread, of course). Less talk, more examples:

```<code>/* These two snippets should do exactly the same thing */

// the js way
var url = 'file.txt';
fetch(url)
    .then(function (data) {
        data = "(" + data + ")";
        return sendToServer(data);
    }).then(function (response) {
        console.log(response);
    });

// synchronous-like way
var url = 'file.txt';
var response = sendToServer("(" + fetch(url) + ")");
console.log(response);
</code>```

What is the most elegant way to compile it back to JS?

The criteria, sorted by importance:

Performance

Backwards compatibility

Compiled code readability (not really important)

There are several possible ways to implement it, those three came to my mind:

Using Promises:

f(); a( b() ); would turn into

f().then(function(){ return b() }).then(function(x){ a(x) });

pros: relatively simple to implement, polyfillable back to ES3

cons: creating a new function and a Proxy instance for every function call

Using generators:

f(); a( b() ); would turn into

yield f(); tmp = yield b(); yield a( tmp );

pros: nicer javascript

cons: creating proxies, generators and iterators on every step, also not polyfillable

EDIT: in fact they are polyfillable using another recompiler (eg. Regenerator)

Using synchronous XMLHttpRequest:

request a server script which waits until another call from somewhere else in the code

pros: de facto no changes in the code, super-easy to implement

cons: requires server script (=>no portability, browser-only); furthermore, synchronous XMLHttpRequest blocks the thread so it does not work at all

EDIT: It actually would work inside a Worker

The main problem is that one can't tell if a function is asynchronous until runtime. That results in the two solutions that at least do work being a lot slower than pure JS. So I ask:

Are there any better ways to implement?

From answers:

Await keyword (@MI3Guy)

C# way (which is good!)

introduces a new keyword (which can be disguised as a function (1st-class-citizen) that eg. throws if the programmer tries to pass it as an argument)

How to know that function is asynchronous? No other keywords!

Every function that contains await keyword becomes asynchronous?

When the code gets to await, it returns a promise? Else treats as an ordinary function?

答:
Assuming the language is dynamically typed, I can see two different ways this could be handled without knowing at compile time if a call is async.

One approach would be to assume every call could be async. However, this would be incredibly inefficient and produce a lot of extra code. This is essentially what you are doing in option 2.

Another option is to use fibers. Fibers are like lightweight threads that are scheduled by the program. The fiber itself decides when to give up control. However, these require operating system support. As far as I can tell, the only way to use fibers in JavaScript is within node.js. My guess is that if you are compiling to JS that the goal (or at least a goal) is to run on the browser which rules out this option. This would be a more lightweight version of option 3.

Honestly, I would consider adding a keyword like C#'s await. This has a number of advantages in addition to specifying that a function is async. Functions can be called to produce futures without awaiting them immediately. This allows for multiple async operations to occur at once rather than in sequence. Additionally, it is better to be explicit about what operations are async because other code can run while the operation is taking place. If async is automatic, it may be surprising when some data you are using is modified by an external piece of code.

In C# within a method marked as async, the return statement is used to return the value that will be inside the future, not the future itself. Note, however, that the async modifier is not really part of the method signature. await can be used with any method that return a future.

If you don't wish to add an async modifier for functions, you could decide (as you stated) that any function with an await is treated like it has an implicit async modifier. So even if a function has an await, but returns before reaching it, the function should still return a future. I would also recommend exposing some way to convert a value into a completed future that contains the value, especially if there is no way to have that done implicitly by adding the async modifier.


问:
How can I rank teams based off of head to head wins/losses
I'm trying to write an algorithm (specifically in Ruby) that will rank teams based on their record against each other. If a team A and team B have won the same amount of games against each other, then it goes down to point differentials.

Here's an example:

```<code>A beat B two times
B beats C one time
A beats D three times
C bests D two times
D beats C one time
B beats A one time
</code>```

Which sort of reduces to

```<code>A[B] = 2
B[C] = 1
A[D] = 3
C[D] = 2
D[C] = 1
B[A] = 1
</code>```

Which sort of reduces to

```<code>A[B] = 1
B[C] = 1
A[D] = 3
C[D] = 1
D[C] = -1
B[A] = -1
</code>```

Which is about how far I've got

I think the results of this specific algorithm would be:

```<code>A, B, C, D
</code>```

But I'm stuck on how to transition from my nested hash-like structure to the results.

My psuedo-code is as follows (I can post my ruby code too if someone wants):

```<code>For each game(g):
  hash[g.winner][g.loser] += 1
</code>```

That leaves hash as the first reduction above

```<code>hash2 = clone of hash
For each key(winner), value(losers hash) in hash:
  For each key(loser), value(losses against winner):
    hash2[loser][winner] -= losses
</code>```

Which leaves hash2 as the second reduction

Feel free to as me question or edit this to be more clear, I'm not sure of how to put it in a very eloquent way. Thanks!

答:
If this is a real life problem, then you must expect inconsistent data, like A beats B, B beats C, C beats A. You already showed inconsistent amounts of information: A played B and D three times each, but didn't play C at all.

I'd make a model describing how likely a team is to beat another team, and find values that agree best with the model. For example "every team has a strength from 0 to 10. If a team is stronger by an amount x ≥ 0 than another team, then it will beat that team with probability 1 - exp (-x^2) / 2". So with identical strength chances are even, but a much stronger team is very likely to win most games.

You could start with an initial guess that every team has a strength of 5, and estimate the chances to get the result of your data. Then you modify the data randomly and check if that improves the chances of getting your data.


问:
Recursively parse without resorting to ugly design patterns
I'm currently building a crochet pattern parser in Java, and I've hit upon some trouble. I'll call the language used for input Crochet Pattern Code (CPC).

I have a rather large writeup on the context, it's appended at the end. You probably won't need all of it, so I'll start with:

The Problem

The problem that I'm facing is that I want to add functions, such as expandRepetitions, to change the following:

```<code>1 x repeat(3) - RepeatSymbol(3)
1 x chain - StitchSymbol(Stitch.Type.ch)
</code>```

Into:

```<code>3 x chain - StitchSymbol(Stitch.Type.ch)
</code>```

This is a representation of the ArrayList first containing a RepeatSymbol(3) and a Chain, and thereafter containing three times StitchSymbol(Stitch.Type.ch).

I also want to be able to turn 2{2{ch}} into:

```<code>1 x repeat(2) - RepeatSymbol(2)
1 x SymbolGroup {2{ch}}
</code>```

And into:

```<code>4 x chain - StitchSymbol(Stitch.Type.ch)
</code>```

However, the only way of applying this action not only to the current ArrayList<Symbol>, but also to the ArrayList<Symbol> inside any GroupSymbol. So far, the only thing I've come up with is this:

```<code>public class Parser {

    ...

    public static expandRepetitions(ArrayList<Symbol> input) {
        int pos = 0;

        while (pos < input.size()) {
             /* on encounter with RepeatSimbol, simplify */
             ...
             /* on encounter with GroupSymbol, do this: */
             input.get(pos).expandRepetitions();
        }
    }

    ...
}

public class GroupSymbol {

    ...

    public void expandRepetitions() {
        Parser.expandRepetitions(this.symbolList);
    }

    ...

}
</code>```

However, this seems like a terrible solutions. I think it's very ugly to have to integrate the GroupSymbol so tightly with the Parser, and feel like there should be a better way possible, but can't think of one.

The Question

How can I improve the structure of GroupSymbol (an ArrayList<Symbol> container) and Parser? Parser needs to apply actions upon an ArrayList<Symbol>, which may contain GroupSymbols, which may contain GroupSymbols, and so on, and these actions need to be applied to the whole contents of these GroupSymbols.

For instance, these actions will include the expanding of repetitions and the simplifying of a list of Symbols to not include groups and repetitions.

Background & details of the parser

I'm building a formalized language for crochet, a parser for this language and a visualizer. I'm currently stuck at the parser, specifically the part that simplifies constructions with grouping and repetitions to a flat list.

Disclaimer: I haven't built a parser, compiler, interpreter or language before and have been winging this up till this point. If you see (other) fatal flaws in my parser and/or language, please do point these out and/or point me at resources for learning about this sort of thing.

The parser is structured as follows:

A Parser object with static functions.

A Symbol interface, and a bunch of differt types of Symbol implementations, such as:

StitchSymbol, which has the property that it represents a certain Stitch.Type

GroupSymbol, which stores an ArrayList<Symbol>, and can contain other instances of GroupSymbol.

RepeatSymbol, which stores an int representing a number of repeats of the next item (a stitch, operation such as skip or a group).

A function preprocess to turn a String into an ArrayList of (basic) Symbols. This is done using a simple finite state machine parser.

A few functions to make these lists of Symbols more useable: one to change a BeginGroupSymbol, a bunch of Symbols and an EndGroupSymbol into a single GroupSymbol which contains the bunch, one to expand repetitions, one to simplify the list to simple instructions.

For instance, in preprocess:

ch is turned into a StitchSymbol with Stitch.Type set to 'ch' (a chain, for those familiar with crochet).

{ is turned into a BeginGroupSymbol.

An example input and output:

```<code>10ch<{3sc2{chskdcchsk}}fo
</code>```

Gives:

```<code>1 x repeat(10) - RepeatSymbol(10)
1 x chain - StitchSymbol(Stitch.Type.ch)
1 x reverse - ReverseSymbol()
1 x begin group - BeginGroupSymbol()
1 x repeat(3) - RepeatSymbol(3)
1 x single crochet - StitchSymbol(Stitch.Type.sc)
1 x repeat(2) - RepeatSymbol(3)
1 x begin group - BeginGroupSymbol()
1 x chain - StitchSymbol(Stitch.Type.ch)
1 x skip - SkipSymbol()
1 x double crochet - StitchSymbol(Stitch.Type.dc)
1 x chain - StitchSymbol(Stitch.Type.ch)
1 x skip - SkipSymbol()
2 x end group - EndGroupSymbol()
1 x fasten off - StitchSymbol(Stitch.Type.fo)
</code>```

Then after that, collapseGroups turns it into the following:

```<code>1 x repeat(10) - RepeatSymbol(10)
1 x chain - StitchSymbol(Stitch.Type.ch)
1 x reverse - ReverseSymbol()
1 x GroupSymbol {3sc2{chskdcchsk}}
1 x fasten off - StitchSymbol(Stitch.Type.fo)
</code>```

The string of CPC after the GroupSymbol is constructed from the items in the ArrayList inside the GroupSymbol. It could be expanded to:

```<code>1 x repeat(3) - RepeatSymbol(3)
1 x single crochet - StitchSymbol(Stitch.Type.sc)
1 x repeat(2) - RepeatSymbol(2)
1 x GroupSymbol {chskdcchsk}
</code>```

This inner GroupSymbol could be further expanded, but I think the picture is clear.

For those who crochet, here's a visual explanation as well:

And what it looks like in wool:

答:
What you have written is really a lexer.  Parsers give you the nested structure from your input, whereas lexers just give a sequence of symbols.  You've probably spent a lot of time reinventing the wheel, when you could use a parser generator like antlr to do most of the work.  For example, it only took me around 5 minutes to come up with the following basic grammar for your example case.  It works with the pegjs javascript parser generator:

```<code>start
  = pattern

pattern
  = symbol*

symbol
  = integer symbol / stitch / "{" pattern "}"

stitch
  = "ch" / "<" / "sc" / "sk" / "dc" / "fo"

integer
  = digits:[0-9]+ { return parseInt(digits.join(""), 10); }
</code>```

It generates the following structured output:

```<code>[
   [
      10,
      "ch"
   ],
   "<",
   [
      "{",
      [
         [
            3,
            "sc"
         ],
         [
            2,
            [
               "{",
               [
                  "ch",
                  "sk",
                  "dc",
                  "ch",
                  "sk"
               ],
               "}"
            ]
         ]
      ],
      "}"
   ],
   "fo"
]
</code>```

This sort of form is much easier to perform any sort of transformation you need.  The groups are already properly nested.  The repeat count is already properly associated with what it should repeat by being grouped inside the same array.  Again, this is 5 minutes of work, and I didn't even try to add semantics.  You can make it much cleaner and more useful with not much effort.

Body:
What you have written is really a lexer.  Parsers give you the nested structure from your input, whereas lexers just give a sequence of symbols.  You've probably spent a lot of time reinventing the wheel, when you could use a parser generator like antlr to do most of the work.  For example, it only took me around 5 minutes to come up with the following basic grammar for your example case.  It works with the pegjs javascript parser generator:

start
  = pattern

pattern
  = symbol*

symbol
  = integer symbol / stitch / "{" pattern "}"

stitch
  = "ch" / "<" / "sc" / "sk" / "dc" / "fo"

integer
  = digits:[0-9]+ { return parseInt(digits.join(""), 10); }

It generates the following structured output:

[
   [
      10,
      "ch"
   ],
   "<",
   [
      "{",
      [
         [
            3,
            "sc"
         ],
         [
            2,
            [
               "{",
               [
                  "ch",
                  "sk",
                  "dc",
                  "ch",
                  "sk"
               ],
               "}"
            ]
         ]
      ],
      "}"
   ],
   "fo"
]

This sort of form is much easier to perform any sort of transformation you need.  The groups are already properly nested.  The repeat count is already properly associated with what it should repeat by being grouped inside the same array.  Again, this is 5 minutes of work, and I didn't even try to add semantics.  You can make it much cleaner and more useful with not much effort.


问:
Sorting Sentences by New Words in Each
A very useful learning tool I stumbled across for Chinese was a massive list of sentences that, barring the first 10 or 15, only differed by the ones before by one or two words, or at least as few as possible: The creator had sorted them by relation, obviously starting with a few standard sentences to prevent the first ones from being random and complex.

I am a little confused about how to go about writing my own implementation of such and algorithm. Now bear with me (unless you stopped reading b/c this question is out of line for this site) as I have been called "stupid" by several teachers but I was thinking of this incredibly inefficient algorithm:

Take first sentence (sentence number one)

Cycle through each sentence thereafter and count the number of different words (different from 1st sentence) (by looping through each word of each sentence) - assign a number in an array depicting this.

Cycle again and find those with the lowest associated numbers

If there is one sentence with the lowest number of different words - make that the next sentence in the list (sentence number two)

If there are multiple sentences, sort them by which have the most words in the top 1000 words in the language and thus are most useful

With the selected sentences (with the most similar words to sentence 1) sorted by word frequency, choose the one or ones that are most frequent as sentences 2, 3 etc.

Start all over by checking the next sentence in the sequence against the last one combined with all previous ones to find lowest number of new words across all sentences

For a corpus of 100, 000 sentences, I will be looping millions of times for each few sentences most likely. There must be a better way. My overall goal is as follows:

Have each sentence in the array (sequence, what have you) have as few new words as possible, with "new" words defined as those not present in any previous sentences.

答:
You could look at this as a simple sorting problem. Consider each "word" to be a unique symbol in an alphabet. To make this efficient you might parse all your sentences into tokens, where each token is a unique number representing a unique word. Does word order matter? You did not specify. If it does, then sort the words (or tokens) within each sentence. Now sort all the sentences using your favorite sorting tool. Similar sentences will be naturally grouped together.

On the other hand, what you may really want is not a single sorted list of sentences, but multiple lists, each representing a cluster of words commonly found together. That is considerably harder.

Title: Sorting Sentences by New Words in Each


问:
What's the opposite of primitive?
In java, int, byte and boolean are primitives, while String is not.

This can be contrasted with c where string is a primitive (essentially an array of chars).

What is the term for types that aren't primitive?

答:
The most general term (language agnostic) is a composite data type.

In Java there are several types of composite data type, the most obvious is a Class but an Enum would be another example.

A boxed type is another related term, which is a primitive wrapped in a class to provide an object oriented interface. Examples of this in Java are an int vs. an Integer or a char vs. a Character.

In java, int, byte and boolean are primitives, while String is not.

A String is actually a boxed type. Under the hood it's implemented as a char array just like C and you could use a char array too if you wanted. Obviously most people don't do this as you won't have any of the convenient abstractions provided by the String class.

Here's how the java.lang.String class is implemented in openjdk:

```<code>/** The value is used for character storage. */
private final char value[];
</code>```

As you can see, there's nothing special about a string in Java.

Title: What's the opposite of primitive?

Body:
The most general term (language agnostic) is a composite data type.

In Java there are several types of composite data type, the most obvious is a Class but an Enum would be another example.

A boxed type is another related term, which is a primitive wrapped in a class to provide an object oriented interface. Examples of this in Java are an int vs. an Integer or a char vs. a Character.

In java, int, byte and boolean are primitives, while String is not.

A String is actually a boxed type. Under the hood it's implemented as a char array just like C and you could use a char array too if you wanted. Obviously most people don't do this as you won't have any of the convenient abstractions provided by the String class.

Here's how the java.lang.String class is implemented in openjdk:

/** The value is used for character storage. */
private final char value[];

As you can see, there's nothing special about a string in Java.


问:
What are useful metrics for source code?
What are useful metrics to capture for source code?

How can metrics, like for example (Executable?) Lines of Code or Cyclomatic Complexity help with quality assurance or how are they beneficial in general for the software development process?

答: Remember: All code can be reduced by at least 1 instruction.  All code has at least 1 bug.  Therefore, all code can be reduced to a single instruction which does not work.  Hope that helps!</p>

ContentLicense: CC BY-SA 2.5


答:
In most examples online however, this is exactly what's done

Not sure how; neither WebRequest nor its concrete descendant HttpWebRequest do in fact implement IDisposable, so this

```<code> using (System.Net.WebRequest wr = new System.Net.HttpWebRequest())
 {
     //What?
 }
</code>```

does not compile. In fact what I find when I google around this topic is mostly speculation as to why WebRequest doesn't implement IDisposable...

The MSDN documentation isn't by any means perfect, but does tell you when a class implements IDisposable; see for example the Remarks section for  StreamWriter.

Title: How do you find out what resources are unmanaged?

Body:
Looking through the .NET documentation, specifically the WebRequest class, I don't see any information indicating that I should wrap an instantiation of it in a using statement. Even the provided example does not do this. In most examples online however, this is exactly what's done.

My question is then, how do I know specifically which classes need to be disposed? Is there a general rule of thumb or do you inspect class definitions to see if they somehow handle unmanaged resources?

Body:
In most examples online however, this is exactly what's done

Not sure how; neither WebRequest nor its concrete descendant HttpWebRequest do in fact implement IDisposable, so this

 using (System.Net.WebRequest wr = new System.Net.HttpWebRequest())
 {
     //What?
 }

does not compile. In fact what I find when I google around this topic is mostly speculation as to why WebRequest doesn't implement IDisposable...

The MSDN documentation isn't by any means perfect, but does tell you when a class implements IDisposable; see for example the Remarks section for  StreamWriter.


问:
Pattern matching against two similar types
What is the best way to handle pattern matching in the following situation?

sealed trait Metadata
final case class Metadata1() extends Metadata
final case class Metadata2() extends Metadata
final case class Metadata3() extends Metadata

sealed trait Data
final case class Data1() extends Data
final case class Data2() extends Data
final case class Data3() extends Data

(metadata, data) match {
    case (Metadata1(), Data1()) =>
    case (Metadata2(), Data2()) =>
    case (Metadata3(), Data3()) =>
}
```

In this example, metadata would usually remain the same, but data may be updated frequently.

Normally a compiler would complain if there is a case that is not handled. However, situations where, for instance, metadata is Metadata1 and b is Data2 would be considered an error condition and should all be handled by the same error handler. If we add a catch all case then the compiler won't give any warnings if Metadata4 and Data4 are added. What is the best way to handle a situation like this?

答:
You call the types "similar", but they're only similar to you. Compiler knows nothing of this similarity, so you either need the compiler to learn about it, or alleviate it somehow.  Here are some possible solutions that I would consider in this situation:

Bite the bullet and list all the cases (aka the quick one)

Before considering more involved possibilities, remember you can always simply list all the cases. You have m * n cases there, so it should be manageable up to 4 or maybe 5 cases each if you squint enough.

In F# you have something called active patterns which let you define a custom way to divide the domain you're matching against. You can use that to encapsulate the verbose matching part and reuse it in subsequent matches. Scala has extractors which supposedly are comparable to active patterns.

Certainly this doesn't scale well.

Add the missing type (aka the correct one)

The observation that MetadataX and DataX types are supposedly similar, but the compiler doesn't know about it, would imply that there's an intermediate type that's missing from the picture. You can introduce that type and it will simply make the entire matching problem disappear.

```<code>type DataSet =
    | DataSet1 of Metadata1 * Data1
    | DataSet2 of Metadata2 * Data2
    | DataSet3 of Metadata3 * Data3
</code>```

Of course, whether that makes things easier depends on how you will construct the instances of that type. I guess that you might have all the Metadatas on hand, and it's only a matter of getting the right one for the Data you're handed, but I'd really need to know more of the picture here.

Break up the match (aka the pragmatic one)

If there's too many cases to handle and you can't add the missing type for some reason, you can always restructure the match expression. You'd need to extract some common logic into functions, and you'd lose some readability, but at least you get around the combinatorial explosion of cases and still keep the "case unhandled" warnings. The code is in F#, but you can treat it as pseudo-code (less verbose than Scala anyway):

```<code>match data with
| Data1 d ->
    match metadata with
    | Metadata1 md -> (* the proper logic goes here *)
    | other        -> (* handle the unmatched types here using a common function *)
| Data2 d ->
    match metadata with
    | Metadata2 md -> (* the proper logic goes here *)
    | other        -> (* handle the unmatched types here using a common function *)
(...)
</code>```

With this, you still have the exhaustive match on the Data cases, and the nested matches give only a slight overhead to each case.

I imagine it could be made even nicer by refactoring the nested matches into functions that pick one of two continuations depending on a Boolean check whether Data and Metadata types fit together.

Body:
You call the types "similar", but they're only similar to you. Compiler knows nothing of this similarity, so you either need the compiler to learn about it, or alleviate it somehow.  Here are some possible solutions that I would consider in this situation:

Bite the bullet and list all the cases (aka the quick one)

Before considering more involved possibilities, remember you can always simply list all the cases. You have m * n cases there, so it should be manageable up to 4 or maybe 5 cases each if you squint enough.

In F# you have something called active patterns which let you define a custom way to divide the domain you're matching against. You can use that to encapsulate the verbose matching part and reuse it in subsequent matches. Scala has extractors which supposedly are comparable to active patterns.

Certainly this doesn't scale well.

Add the missing type (aka the correct one)

The observation that MetadataX and DataX types are supposedly similar, but the compiler doesn't know about it, would imply that there's an intermediate type that's missing from the picture. You can introduce that type and it will simply make the entire matching problem disappear.

type DataSet =
    | DataSet1 of Metadata1 * Data1
    | DataSet2 of Metadata2 * Data2
    | DataSet3 of Metadata3 * Data3

Of course, whether that makes things easier depends on how you will construct the instances of that type. I guess that you might have all the Metadatas on hand, and it's only a matter of getting the right one for the Data you're handed, but I'd really need to know more of the picture here.

Break up the match (aka the pragmatic one)

If there's too many cases to handle and you can't add the missing type for some reason, you can always restructure the match expression. You'd need to extract some common logic into functions, and you'd lose some readability, but at least you get around the combinatorial explosion of cases and still keep the "case unhandled" warnings. The code is in F#, but you can treat it as pseudo-code (less verbose than Scala anyway):

match data with
| Data1 d ->
    match metadata with
    | Metadata1 md -> (* the proper logic goes here *)
    | other        -> (* handle the unmatched types here using a common function *)
| Data2 d ->
    match metadata with
    | Metadata2 md -> (* the proper logic goes here *)
    | other        -> (* handle the unmatched types here using a common function *)
(...)

With this, you still have the exhaustive match on the Data cases, and the nested matches give only a slight overhead to each case.

I imagine it could be made even nicer by refactoring the nested matches into functions that pick one of two continuations depending on a Boolean check whether Data and Metadata types fit together.


问:
Atlassian Bamboo package from multiple repositories
We're currently developing a server/client application. The server is a maven Java EE project. The client interfaces are in HTML5. We use Stateless REST interfaces to communicate with each other. As there are two subteams in our project team, we decided it was a good thing to separate the server and client interfaces in two git repositories (web dev team doesn't need the server for developing/testing interfaces, and vice versa).

However, when it comes to packaging, we use git subtrees to install the web interfaces in the server projet before launching mvn package.

We recently have felt the need for a CI server, and we went for Bamboo, as we already use Jira and Confluence in our company.

Is there a way to make Bamboo actually do the web interfaces integration before packaging so we don't have to use git subtree?

答:
It is possible to build from two repos in one Bamboo plan.

Build plans allow multiple repositories.  The first and default task in a plan is a source code checkout for the repo.  You can then add another source code checkout task for the second repo (with an optional checkout directory)

The other option is to have a build plan for your web interfaces that gets shared as an artifact.  Then the server build plan can download the web artifact using the "Artifact download" task.


问:
How to avoid server-pushing assets to clients that already have them cached?
HTTP/2 server push enables pushing assets to clients which you anticipate they'll need in order to render the page. For example, you can push your CSS/JS/images to the client at the same time as you respond to a request for an HTML page, so they receive those assets sooner.

But how do you avoid wasting bandwidth on clients that already have the assets cached?

Does the server push mechanism handle this situation automatically, and how? Or does my serverside app need to somehow track clients that have already been served a response previously, and avoid server-pushing extra assets to those clients?

答:
Read the spec http://http2.github.io/http2-spec/#PushResources, it notes that cacheable responses will be cached, non-cacheable responses must not be cached.

If something is already in the cache, the client will be able to refuse the duplicate asset by sending a RST_STREAM frame: http://http2.github.io/http2-spec/#RST_STREAM.

See mark Nottingham's blog for more details:

https://www.mnot.net/blog/2014/01/30/http2_expectations

He also indicates that server push will allow the server to proactively invalidate the client's cache, i.e. push a new asset when the server asset has changed, which is a very useful feature.


问:
Dynamic Code Evaluation in Java - Clever or Sloppy?
I am trying to create a flexible ACL framework in Java for my application.

Many ACL frameworks are built on a whitelist of rules, where a rule is in the form of owner:action:resource.  For example,

"JOHN can VIEW resource FOOBAR-1"

"MARY can VIEW resource FOOBAR-1"

"MARY can EDIT resource FOOBAR-1"

This is attractive because the rules can easily be serialized/persisted to a database.  But my application has complex business logic.  For example,

"All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized"

"All users in department 2, if the date is after 03/15/2016, can VIEW resource FOOBAR-2, else not authorized"

Upon first thought, it would be a nightmare to devise a database schema that could handle infinitely complex rules such as these.  Therefore, it seems as though I would need to "bake" them into the compiled application, evaluate them for each user, and then produce owner:action:resource rules as a result of the evaluation.  I want to avoid baking the logic into the compiled application.

So, I was thinking of representing a rule in the form of predicate:action:resource, where the predicate is a boolean expression that determines whether a user is allowed.  The predicate would be a string of a JavaScript expression that could be evaluated by Java's Rhino engine.  For example,

return user.getDept() == 1 && user.seniority > 5;

In doing so, the predicates could easily be persisted to the database.

Is this clever?  Is this sloppy?  Is this gimmicky?  Is this over-engineered?  Is this safe (apparently, Java can sandbox the Rhino engine).

答:
We did this at my current company, and we're very happy with the results.

Our expressions are written in js, and we even use them to restrict the results the users can get from querying ElasticSearch.

The trick is making sure that enough info is available to make the decision, so that you can really write whatever perms you want without code changes, but at the same time keeping it fast.

We are not really worried with code injection attacks, as the permissions are written by those that have no need to attack the system. And the same applies to DOS attacks like the while(true) example. The admins of the system have no need to do that, they could just remove everybody's permissions...

Update:

Something like XACML seems to be better as a central auth management point for an organization. Our use case is slightly different in that our clients tipically have not an IT department to run all that. We needed something self-contained but tried to preserve as much flexibility as possible.


问:
How accurate is "Business logic should be in a service, not in a model"?
Situation

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?

答:
I think the answer is clear if you read Martin Fowler's Anemic Domain Model article.

Removing the business logic, which is the domain, from the domain model is essentially breaking object oriented design.

Let's review the most basic object oriented concept: An object encapsulates data and operations. For instance, closing an account is an operation that an account object should perform on itself; therefore, having a service layer perform that operation is not an object oriented solution.  It is procedural, and it is what Martin Fowler is referring to when he is talking about an anemic domain model.

If you have a service layer close the account, rather than having the account object close itself, you don't have a real account object. Your account "object" is merely a data structure. What you end up with, as Martin Fowler suggests, is a bunch of bags with getters and setters.

ContentLicense: CC BY-SA 4.0


问:
How much should I be using 'let' vs 'const' in ES6?
I've been writing a lot of ES6 code for io.js recently. There isn't much code in the wild to learn from, so I feel like I'm defining my own conventions as I go.

My question is about when to use const vs let.

I've been applying this rule: If possible, use const. Only use let if you know its value needs to change. (You can always go back and change a const to a let if it later turns out you need to change its value.)

The main reason for this rule is it's easy to apply consistently. There are no grey areas.

The thing is, when I apply this rule, in practice 95% of my declarations are const. And this looks weird to me. I'm only using let for things like i in a for loop, or occasionally for things like accumulated Fibonacci totals (which doesn't come up much in real life). I was surprised by this – it turns out 95% of the 'variables' in my ES5 code to date were for values that do not vary. But seeing const all over my code feels wrong somehow.

So my question is: is it OK to be using const this much? Should I really be doing things like const foo = function () {...};?

Or should I reserve const for those kind of situations where you're hard-coding a literal at the top of a module – the kind you do in full caps, like const MARGIN_WIDTH = 410;?

答:
My reply here is not javascript-specific.

As a rule of thumb in any language that lets me do so in a semi-easy way I'd say always use const/final/readonly/whatever it is called in your language whenever possible. The reason is simple, it's much easier to reason about code when it is dead obvious what can change and what cannot change. And in addition to this, in many languages you can get tool support that tells you that you are doing something wrong when you accidentially assign to a variable that you've declared as const.

Going back and changing a const to a let is dead simple. And going const by default makes you think twice before doing so. And this is in many cases a good thing.

How many bugs have you seen that involved variables changing unexpectedly? I'd guess a lot. I know that the majority of bugs that I see involve unexpected state changes. You won't get rid of all of these bugs by liberally using const, but you will get rid of a lot of them!

Also, many functional languages have immutable variables where all variables are const by default. Look at Erlang for example, or F#. Coding without assignment works perfectly in these languages and is one of the many reasons why people love functional programming. There is a lot to learn from these languages about managing state in order to become a better programmer.

And it all starts with being extremely liberal with const! ;) It's just two more characters to write compared to let, so go ahead and const all the things!


问:
SRS document and version control
When working on relatively small projects, but a software requirement specification document is necessary, is it a standard to include said document on version control systems or is it managed differently. Note I'm talking about standards</p>

答:
Yes and no. Version control is about just that: control of revisions of assets, be they source code text files, images, or even documentation. While software engineers usually put source code and graphical assets (once they receive them) under version control, graphical assets and standards documents are often prepared by non-engineers. In my experience, these people rarely work under version control (though it could be argued that they should).

Another reason why requirements specifications are not often under version control is that they are often not text files (Word documents, spreadsheets, or Google documents are common) and thus versions cannot be compared easily by many version control systems. Yes, modern word processors can intelligently compare different revisions, but sometimes that feature cannot be invoked by the version control system.

In spite of this, there is a natural tendency for people to understand the importance of preserving old versions, and I have seen various ad hoc methods used by non-engineers, like adding revision numbers or dates to the filenames, for instance.

You ask about standards, and I know of no commonly-applied official standards requiring which assets need to be under version control and which do not. This is a managerial and organizational choice, and it varies from place to place. Some enterprises have clear policy around this, using in-house or externally-defined guidelines, or special software tools, others do not.

OwnerDisplayName: Christopher Francisco

Title: SRS document and version control

OwnerDisplayName: Randall Cook


问:
is there a cleaner / simpler way to code this?
I have a web app that uses ajax to filter db results.
So if you have a list of 1000 widgets, that have IDs ranging from 1-1000, by typing numbers into the ID field, you can narrow your search.
Typing the number 9 will automatically query the db to return only records that have an id that start with 9 etc...
The same type of a feature exists for widget names.

Here's what the code looks like in part, as far as querying is concerned:

```<code>get_widgets = function(id, name)
        local sql
        if name==nil and id==nil then
                sql = "SELECT * FROM widgets"
        elseif addr == nil then
                sql = "SELECT * FROM widgets WHERE id LIKE '"..id.."%'"
        elseif tn==nil then
                sql = "SELECT * FROM widgets WHERE name LIKE '"..name.."%'"
        else
                sql = "SELECT * FROM widgets WHERE id LIKE '"..id.."%' AND name LIKE '"..name.."%'"
        end

      ... logic to connect to db and execute query.
end
</code>```

Just wondering if there's a more elegant way to do this.
or if what I have is ok.

答:
SQL concatenation applications like this benefit from a technique which I will call "1=1".  I don't know Lua, so I'm going to use "pseudo-Lua."

```<code>sql = "SELECT * FROM widgets WHERE 1=1 "

if id != nil then
    sql += "AND id LIKE '"..id.."%'"

if name != nil then
    sql += "AND name LIKE '"..name.."%'"
</code>```

If you still need the elseif exclusivity, the only thing you can really do is start off with SELECT * FROM widgets, and tack on the WHERE clause in the elseif.

Body:
SQL concatenation applications like this benefit from a technique which I will call "1=1".  I don't know Lua, so I'm going to use "pseudo-Lua."

sql = "SELECT * FROM widgets WHERE 1=1 "

if id != nil then
    sql += "AND id LIKE '"..id.."%'"

if name != nil then
    sql += "AND name LIKE '"..name.."%'"

If you still need the elseif exclusivity, the only thing you can really do is start off with SELECT * FROM widgets, and tack on the WHERE clause in the elseif.


问:
Licensing of content created by licensed code
So I had been using trianglify, and I was thinking about using an image that it had created. Trianglify is licensed under GPLv3, however, (as I understand it,) it creates unique svg files. The author has not included any instructions as to how to source/license these images, so I was thinking about sourcing the image in my GitHub .readme file for my project.

My question is, would I have to also change the licensing of my code to be under the GPLv3 if I am only using an image derived from the licensed product? What should I do? I'm not using any of the code, just its (unique) product (an image). Or would this be on a case by case basis where I would have to contact the author (if so, for each usage or just once)?

答: Author here. Trianglify images are yours to do whatever you want with. You could even trademark a trianglify image to use in a logo. It's just a tool, what you produce using the tool is content that you own.</p>


答:
This case is explained in the GNU GPL FAQ:

Is there some way that I can GPL the output people get from use of my program? For example, if my program is used to develop hardware designs, can I require that these designs must be free?

In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert his own data, the copyright on the output belongs to him, not you. More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.

So the only way you have a say in the use of the output is if substantial parts of the output are copied (more or less) from text in your program. For instance, part of the output of Bison (see above) would be covered by the GNU GPL, if we had not made an exception in this specific case.

You could artificially make a program copy certain text into its output even if there is no technical reason to do so. But if that copied text serves no practical purpose, the user could simply delete that text from the output and use only the rest. Then he would not have to obey the conditions on redistribution of the copied text.

In what cases is the output of a GPL program covered by the GPL too?

Only when the program copies part of itself into the output.

So no, the output of a GNU GPL program is not covered by the GNU GPL and you can put it under any license conditions you want.

<advertising>When you have more questions about open source licenses, you might want to commit to the new proposal Open Source Stackexchange. It still needs people to commit to it so it can go into beta phase.</advertising>

Title: Licensing of content created by licensed code

Body:
So I had been using trianglify, and I was thinking about using an image that it had created. Trianglify is licensed under GPLv3, however, (as I understand it,) it creates unique svg files. The author has not included any instructions as to how to source/license these images, so I was thinking about sourcing the image in my GitHub .readme file for my project.

My question is, would I have to also change the licensing of my code to be under the GPLv3 if I am only using an image derived from the licensed product? What should I do? I'm not using any of the code, just its (unique) product (an image). Or would this be on a case by case basis where I would have to contact the author (if so, for each usage or just once)?


问:
Is it conventional to name final/constant local variables in UPPER_SNAKE_CASE?
Pretty simple, I have a method:

```<code>public final void myMethod(User user, Group group) {
    final int MAX_USERS_PER_GROUP = group.getMaxUsersPerGroup();
    int usersInGroup = 0;

    // Get users in group and all subgroups, recursively

    if (usersInGroup > MAX_USERS_PER_GROUP) {
        throw new Exception(...);
    }
}
</code>```

But according to Eclipse:

This name is discouraged. According to convention, names of local variables should start with a lowercase letter.

My worry is that this will get flagged as bad code, even thought it is by all accounts a constant and should be formatted as such.

答:
The code and naming conventions for Java are fairly well established. In particular, this one (or its mismatch) can be seen in Section 9 - Naming Conventions

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

```<code>static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;
</code>```

The key point is that this is a variable in the example code.  Its one that you've given the hint to other coders that once assigned it can't be changed - but it is not a constant.  Furthemore, it isn't a class constant.

```<code>public final void myMethod(User user, Group group) {
    final int MAX_USERS_PER_GROUP = group.getMaxUsersPerGroup();
    int usersInGroup = 0;

    // Get users in group and all subgroups, recursively

    if (usersInGroup > MAX_USERS_PER_GROUP) {
        throw new Exception(...);
    }
}
</code>```

This would be incorrect according to the naming standards.

You may wish to look into running checkstyle.  The naming conventions checks for this are in accordance with Java naming conventions.

The local final variable check is:

```
LocalFinalVariableName
    local, final variables, including catch parameters
    ^[a-z][a-zA-Z0-9]*$
```

It starts with a lower case and does not include underscores.  Of course, your team could vary from this Java standard, and tweak checkstyle's rules to make sure that you are all following the same convention - though you will confuse other Java coders who look at the code.

Body:
The code and naming conventions for Java are fairly well established. In particular, this one (or its mismatch) can be seen in Section 9 - Naming Conventions

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;

The key point is that this is a variable in the example code.  Its one that you've given the hint to other coders that once assigned it can't be changed - but it is not a constant.  Furthemore, it isn't a class constant.

public final void myMethod(User user, Group group) {
    final int MAX_USERS_PER_GROUP = group.getMaxUsersPerGroup();
    int usersInGroup = 0;

    // Get users in group and all subgroups, recursively

    if (usersInGroup > MAX_USERS_PER_GROUP) {
        throw new Exception(...);
    }
}

This would be incorrect according to the naming standards.

You may wish to look into running checkstyle.  The naming conventions checks for this are in accordance with Java naming conventions.

The local final variable check is:

LocalFinalVariableName
    local, final variables, including catch parameters
    ^[a-z][a-zA-Z0-9]*$

It starts with a lower case and does not include underscores.  Of course, your team could vary from this Java standard, and tweak checkstyle's rules to make sure that you are all following the same convention - though you will confuse other Java coders who look at the code.


答:
Constants are things given values that are known before or during compilation.

What you've declared is a variable because its value is determined at runtime by invoking a method.  The fact that it's final is really just a convenience for letting the compiler know that once the value is set, it won't be changed.

Title: Is it conventional to name final/constant local variables in UPPER_SNAKE_CASE?

Body:
Pretty simple, I have a method:

```<code>public final void myMethod(User user, Group group) {
    final int MAX_USERS_PER_GROUP = group.getMaxUsersPerGroup();
    int usersInGroup = 0;

    // Get users in group and all subgroups, recursively

    if (usersInGroup > MAX_USERS_PER_GROUP) {
        throw new Exception(...);
    }
}
</code>```

But according to Eclipse:

This name is discouraged. According to convention, names of local variables should start with a lowercase letter.

My worry is that this will get flagged as bad code, even thought it is by all accounts a constant and should be formatted as such.


答:
Although I agree with most of Randall Cook's answer, I would like to add some additional things.

Your requirements should be under configuration management and be controlled in some way. That is, you should be able to associate a given set of requirements (perhaps captured in a SRS document or a collection of user stories or a database or some other format) to a given software version. For any given software version, you'd probably want to know what the requirements, design, implementation (source code), test cases (test code, scripts, manual procedures), and perhaps even test results are. This aspect of configuration management is called "configuration identification".

One aspect of configuration management is version control. However, how you implement version control could be different depending on the type of artifact. Source code could be kept in tools that are well-suited to managing software (which is usually text files) - tools like Subversion or git. However, different tools may be necessary to properly version other artifacts. Requirements management tools, such as DOORS, often have change management workflows and support the versioning of requirements. For documents, a content management system may allow you to track versions as well.

As far as standards go, there are standards for configuration management, there are many, some active and some withdrawn or superseded - ANSI, ISO, IEEE, the US Department of Defense, industry specific practices for a number of different industries, and so on. How applicable they are to you depends on a various factors - contractual or regulatory obligations, project size and type, industry, to name a few big ones. They may provide guidance and a starting point for tailoring. Ultimately, though, it's up to the development organization to define a process that is suitable for their needs.

Title: SRS document and version control

Body: When working on relatively small projects, but a software requirement specification document is necessary, is it a standard to include said document on version control systems or is it managed differently. Note I'm talking about standards</p>