问:
Working with static constructor in Java
I didn't get a complete understanding of static constructors in Java. If it is allowed, why it is allowed? In what scenarios would you use it? What purpose would it serve? Can someone give me a simple example please?</p>

答:
Gurgadurgen's answer is probably what you're looking for, but I'll just add a couple of other points that are sometimes neglected when someone wants a "static constructor".

If you want a static method that creates an instance of your class, you can create a static method that simply invokes the class's constructor.

```<code>public class Example
{
    /** Static method to create an instance. */
    public static Example build()
    { return new Example() ; }

    /** A field of each instance. */
    private String stuff ;

    /** The class's actual constructor. */
    public Example()
    { stuff = new String() ; }

    public String getStuff()
    { return this.stuff ; }

    /**
     * Mutator for "stuff" property. By convention this returns "void"
     * but you might want to return the object itself, to support the
     * sort of chained invocations that are becoming trendy now. You'll
     * see the stylistic benefits of chaining later in this example.
     */
    public Example setStuff( String newStuff )
    {
        this.stuff = newStuff ;
        return this ;
    }
}

public class ExampleTest
{
    public static void main( String[] args )
    {
        // The usual instance model.
        Example first = new Example() ;
        System.out.println( first.setStuff("stuff").getStuff() ) ;

        // Using your static method to construct an instance:
        Example second = Example.build() ;
        System.out.println( second.setStuff("more stuff").getStuff() ) ;

        // Chaining all the invocations at once:
        System.out.println( Example.build().setStuff("even more stuff").getStuff() ) ;
    }
}
</code>```

This produces the output:

```<code>stuff
more stuff
even more stuff
</code>```

The other reason to make a static method to construct an instance is the case when you want to ensure that exactly one instance of your class exists at any given time; this is called a singleton. By convention, such a class would provide a static method called getInstance() to get the one and only instance that is treated as a "singleton".

```<code>public class SingletonExample extends Example
{
    // Note: This extends my previous example, which has a "stuff"
    // property, and a trivial constructor.

    /** The singleton instance, statically initialized as null. */
    private static SingletonExample singleton = null ;

    /**
     * The static accessor for the singleton. If no instance exists,
     * then it will be created; otherwise, the one that already exists
     * will be returned.
     */
    public static SingletonExample getInstance()
    {
        if( singleton == null )
            singleton = new SingletonExample() ;
        return singleton ;
    }
}

public class SingletonExampleTest
{
    public static void main( String[] args )
    {
        System.out.println( SingletonExample.getInstance().setStuff("stuff").getStuff() ) ;

        // You could still create instances of this class normally if you want to.
        SingletonExample otherstuff = new SingletonExample() ;
        otherstuff.setStuff("other stuff") ;

        // But watch what happens to this.
        System.out.println( SingletonExample.getInstance().getStuff() ) ;
        System.out.println( otherstuff.getStuff() ) ;

        // Now we show what happens when you start modifying the singleton.
        SingletonExample theoneandonly = SingletonExample.getInstance() ;
        theoneandonly.setStuff("changed stuff") ;
        System.out.println( SingletonExample.getInstance().getStuff() ) ;
    }
}
</code>```

This produces the following.

```<code>stuff
stuff
other stuff
changed stuff
</code>```

By storing a reference to the singleton, and then modifying it, the next call to getInstance() gets that modified singleton.

It's tempting to use singletons as a way to start creating global variables for your application. In some contexts this can be useful, but it can also get you into trouble. In particular I ran into an interesting bug while developing an Android app, where singleton instances could get lost. Jumping from one activity to another can sometimes lead the JVM to use a new "class loader" which won't know about the singleton that was stored statically by a previous class loader.

Title: Working with static constructor in Java

Body:
Gurgadurgen's answer is probably what you're looking for, but I'll just add a couple of other points that are sometimes neglected when someone wants a "static constructor".

If you want a static method that creates an instance of your class, you can create a static method that simply invokes the class's constructor.

public class Example
{
    /** Static method to create an instance. */
    public static Example build()
    { return new Example() ; }

    /** A field of each instance. */
    private String stuff ;

    /** The class's actual constructor. */
    public Example()
    { stuff = new String() ; }

    public String getStuff()
    { return this.stuff ; }

    /**
     * Mutator for "stuff" property. By convention this returns "void"
     * but you might want to return the object itself, to support the
     * sort of chained invocations that are becoming trendy now. You'll
     * see the stylistic benefits of chaining later in this example.
     */
    public Example setStuff( String newStuff )
    {
        this.stuff = newStuff ;
        return this ;
    }
}

public class ExampleTest
{
    public static void main( String[] args )
    {
        // The usual instance model.
        Example first = new Example() ;
        System.out.println( first.setStuff("stuff").getStuff() ) ;

        // Using your static method to construct an instance:
        Example second = Example.build() ;
        System.out.println( second.setStuff("more stuff").getStuff() ) ;

        // Chaining all the invocations at once:
        System.out.println( Example.build().setStuff("even more stuff").getStuff() ) ;
    }
}

This produces the output:

stuff
more stuff
even more stuff

The other reason to make a static method to construct an instance is the case when you want to ensure that exactly one instance of your class exists at any given time; this is called a singleton. By convention, such a class would provide a static method called getInstance() to get the one and only instance that is treated as a "singleton".

public class SingletonExample extends Example
{
    // Note: This extends my previous example, which has a "stuff"
    // property, and a trivial constructor.

    /** The singleton instance, statically initialized as null. */
    private static SingletonExample singleton = null ;

    /**
     * The static accessor for the singleton. If no instance exists,
     * then it will be created; otherwise, the one that already exists
     * will be returned.
     */
    public static SingletonExample getInstance()
    {
        if( singleton == null )
            singleton = new SingletonExample() ;
        return singleton ;
    }
}

public class SingletonExampleTest
{
    public static void main( String[] args )
    {
        System.out.println( SingletonExample.getInstance().setStuff("stuff").getStuff() ) ;

        // You could still create instances of this class normally if you want to.
        SingletonExample otherstuff = new SingletonExample() ;
        otherstuff.setStuff("other stuff") ;

        // But watch what happens to this.
        System.out.println( SingletonExample.getInstance().getStuff() ) ;
        System.out.println( otherstuff.getStuff() ) ;

        // Now we show what happens when you start modifying the singleton.
        SingletonExample theoneandonly = SingletonExample.getInstance() ;
        theoneandonly.setStuff("changed stuff") ;
        System.out.println( SingletonExample.getInstance().getStuff() ) ;
    }
}

This produces the following.

stuff
stuff
other stuff
changed stuff

By storing a reference to the singleton, and then modifying it, the next call to getInstance() gets that modified singleton.

It's tempting to use singletons as a way to start creating global variables for your application. In some contexts this can be useful, but it can also get you into trouble. In particular I ran into an interesting bug while developing an Android app, where singleton instances could get lost. Jumping from one activity to another can sometimes lead the JVM to use a new "class loader" which won't know about the singleton that was stored statically by a previous class loader.


问:
Does a Form describing JSON "Standard" exist?
I joined a project were we sell services for different providers through web, iOS and android apps. I am working on iOS. I was ask to display a purchase form via a web view and react by what is entered natively. I do so by intercepting the network communication but as you can imagine it is slow, error prone and just kind of stupid.
I ask why it has to be done in this way, why I just cannot get the data and render the form myself natively, and I was told that soon also the android app will adapt this feature and as the form can slightly change for each providers that would be the easiest approach.

While I agree that it is easier to decide on the server which fields are needed for each call, I don't think that the logical conclusion is to request a html form and create hackish interception around it.

Before the implementation for android starts I want to propose another option:

Instead of rendering a website I want the server to create a JSON to describe the form, that than can easily be used at client-side to create the form. Basically a server generated view model.

My question is: is there some "standard" already how such a JSON should look like?

I imagine it something like this

```<code>{
  "form": {
    "action": {
      "action-name": "Send",
      "method": "POST",
      "target": "https://api.mydomain.com/purchase/"
    },
    "fieldsets": [{
      "fieldset-name": "personal information",
      "fields": [{
        "field": {
          "kind": "text-field",
          "field-name": "First Name",
          "validator": {
            "validator-name": "regex-validator",
            "arguments": [{
              "regex": ".{3:}"
            }]
          },
          "optional": false
        }
      }, {
        "field": {
          "kind": "text-field",
          "field-name": "Last Name",
          "validator": {
            "validator-name": "regex-validator",
            "arguments": [{
              "regex": ".{3:}"
            }]
          },
          "optional": false
        }
      }, {
        "field": {
          "kind": "text-field",
          "field-name": "Email",
          "validator": {
            "validator-name": "email-validator"
          },
          "optional": false
        }
      }, {
        "field": {
          "kind": "text-field",
          "field-name": "Confirm Email",
          "validator": {
            "validator-name": "email-validator"
          },
          "optional": false
        }
      }]
    }, {
      "fieldset-name": "Credit Card Data",
      "fields": [{
        "field": {
          "kind": "text-field",
          "field-name": "Credit Card Number",
          "validator": {
            "validator-name": "creditcard-number-validator"
          },
          "optional": false
        }
      }]
    }]
  }
}
</code>```

答: I think the standard you are looking for is JSON Schema. It's not specific to forms, it's a more general specification for defining what a particular JSON format looks like (like an XML schema). There are a few solutions for creating forms with JSON Schema, like joshfire/jsonform.</p>

ContentLicense: CC BY-SA 3.0


问:
Is checking return values always required?
We know that checking return values prevent our software from unexpected states. (You can see CWE definition.)
But, we are sometimes sure about the return value. For example:

```<code>bool calculateSquareRootReturnFalseIfInputIsNegative(float input, float& output);
float calculateHypotenuse(float a, float b){
  float c2 = (a*a) + (b*b);
  float c;
  calculateSquareRootReturnFalseIfInputIsNegative(c2, c);
  return c;
}
</code>```

The local variable c2 is always positive. So, calculateSquareRootReturnFalseIfInputIsNegative() always returns true. I shouldn't check its return value.

Finally, Is "check all return values not already known by caller" a valid idiom?

Thanks..

答:
That depends upon what you mean.  If you mean is it required in order to output the correct result, the answer is no.  If you mean is it required in order for the code to be well written, then the answer is yes.

Well written code is code that is unambiguous to the reader -- if I read your code and see you ignore a return value, I have to break out my psychic abilities and determine if you INTENTIONALLY or INADVERTANTLY ignored the return value in order to understand what you meant the code to do.  My psychic abilities are notorious for returning ambiguous results.

More seriously, an empty if block (with or without a comment) makes it clear that you know about the return value (and that it wasn't for instance added as part of a refactoring) and that you considered what to do.  It also provides a handy starting point to add the code to handle the return value if it turns out that it needs to be handled after all.


问:
many to many relation in database schema and oop class diagram
I have Student and Group entities. Student can have many groups and Group can have many students too. so in database I should have middle class and change many-to-many relation to one-to-many and many-to-one.

My question is how should I design class diagram in oop?

If middle table does not have any extra field(just student_id and group_id) then I think no middle class is need in oop, is this true or not?

答: That is correct. You simply have a property of groups (which makes more sense to me than students, but that's a matter of opinion) that is an enumerable collection of students that belong to the group.</p>


问:
Massive View Controller - IOS - Solutions
I'm sure every new iOS developer has the following problem: The View Controllers get very fast crowded with code for various purposes, easily getting to 500 + lines of code.

This is how it looks like for two basic and common screens:

1) The Form Screen:

2) The Table View Controller Screen

So far I have read about two different solutions:

First Solution: https://bendyworks.com/single-responsibility-principle-ios/.
This is based on Notifications, it completely separates the View Controller from the (Intentions) View Model and thus reduces code in the View Controller.
I think that it has the downside of breaking code, similar to Go-To structures.
It looks like this:

The second solution keeps the same crowded View Controllers (button actions are executed inside VC and so on). but uses libraries like TPKeyboardAvoiding, BlocksKit or other solutions most of them based on categories. With this second solution, code is drastically reduced but the view controller still has a lot of responsibility.

What do you think about these solutions? Which is better? Is there a better one?

答:
We can use MVVM to resolve this issue.

The Model-View-ViewModel, or MVVM pattern as it’s commonly known, is a UI design pattern. VM takes all logic about preparing model data for UI from VC.

Example:

You have got model object with some fields, you want to format some of them, make calculation and combine them.

In MVC case all that logic located in ViewController.

In MVVM you move all of it from VC to VM.

VM will prepare all data for UI and VC just sets it like this.

(in VC class)

```<code>self.descriptionLabel = self.viewModel.textForDescriptionLabel;
</code>```

Tutorials and topics:

Introduction to MVVM

MVVM Tutorial with ReactiveCocoa

iOS Design Patterns: MVC and MVVM

Body:
We can use MVVM to resolve this issue.

The Model-View-ViewModel, or MVVM pattern as it’s commonly known, is a UI design pattern. VM takes all logic about preparing model data for UI from VC.

Example:

You have got model object with some fields, you want to format some of them, make calculation and combine them.

In MVC case all that logic located in ViewController.

In MVVM you move all of it from VC to VM.

VM will prepare all data for UI and VC just sets it like this.

(in VC class)

self.descriptionLabel = self.viewModel.textForDescriptionLabel;

Tutorials and topics:

Introduction to MVVM

MVVM Tutorial with ReactiveCocoa

iOS Design Patterns: MVC and MVVM


答:
You don't need a class for that, but maybe you want one. At the database design level, I like to avoid linking tables and think of those tables as first class entities instead. So if we have student and class tables for example, instead of creating a student_class linking table to satisfy that many-to-many relationship, we could call it something like enrollment.

Now, at the OOP level, we don't have to think about whether we should write something like student.addClass(class) or class.addStudent(student). Instead we can write new Enrollment(student, class). And, if we ever decide that we need to store more data about that relationship, we don't have to deal with awkward problems that come from linking tables having extra fields (especially with respect to ORMs and so on). Since Enrollment is a first-class entity, it can have any other properties we want in addition to student and class.

If you can conceptualize the relationship between a student and a group as its own entity, it would probably be cleanest to model it that way.

Title: many to many relation in database schema and oop class diagram

Body:
I have Student and Group entities. Student can have many groups and Group can have many students too. so in database I should have middle class and change many-to-many relation to one-to-many and many-to-one.

My question is how should I design class diagram in oop?

If middle table does not have any extra field(just student_id and group_id) then I think no middle class is need in oop, is this true or not?


问:
Pattern for caching DAOs: strategy or decorator?
I'm building a php system with the Services/DAOs/Domain Models pattern, and now is the time to implement a caching system for the DAOs.

Would you use a decorator pattern, or maybe the strategy pattern?

What are the ups and downs of each one?

added requirement: Like I told in a comment answering to edalorzo I need to be able to use the DAOs without any caching at some moments. For the same method sometimes is acceptable to have cache, but some other times is not.

答:
I have seen the implementation of caches using a Proxy pattern. Particularly frameworks like AOP make use of proxies for most of these things.

According to the book Design Patterns and Elements of Reusable Object-Oriented Software the decorator and proxy pattern may look alike/

Page 216:

"Although decorators may have similar implementations as proxies,
  decorators have a different purpose. A decorator adds one or more
  responsibilities to an object, whereas a proxy controls access to an
  object.

Proxies vary in the degree to which they are implemented like a
  decorator.A protection proxy might be implemented exactly like a
  decorator. On the other hand, a remote proxy will not contain a direct
  reference to its real subject but only an indirect reference, such as
  a "host ID and local address on the host". A virtual proxy will start
  off with an indirect reference such as a file name but will eventually
  obtain and use a direct reference"

It looks like your purpose with the cache is to avoid giving direct access to the real subject, so it sounds more like a proxy to me.

The comment above also clearly makes evident that an important difference between a proxy and a decorator is that the proxy may be responsible for instantiating or getting access to the real subject, whereas in the case of the decorator is kind of expected that such reference will be dynamically provided.

It would seem that the relationship between the proxy and real subject is more static than in the case of the decorator.

That being said, ultimately in you case is a matter of intent more than how the design will look like. At the end the solution is to have a wrapper object (either called Proxy or Decorator) that will intercept the method and allow you to control when to gain access to a cache or not depending on your cache policy.


问:
Which design is better? [MainClass] -> [Class] OR [MainClass] -> [MiddleClass] -> [Class]
I have two designs which achieve the same result.

```<code>-------Design A
</code>```

MainClass has a List and two methods. The methods create an autonomous object and is added to the list. The reason for the superclass, B and C are similar and I will be adding more subclasses. Furthermore, I can take advantage of polymorphism later on.

```<code>-------Design B
</code>```

mainclass has two methods. The method creates a aggregation link with MiddleClass and directly calls Mainclass methods - which returns an autonomous object of class b/c.

Unlikely A, B benefits from a higher degree of (loose)coupling from the MainClass, where the MiddleClass acts handles information from the inheritance hierarchy to the mainclass - And of course, the more subclasses I add, the mainclass will not have any additional links to the hierarchy, instead, it's all dealt with by middleclass.

However, I am not sure if I am just over-engineering the design or if it's a better design. What do you guys think is the better design and why?

答:
In both designs, MainClass has to know about ClassB and ClassC (and any future derived classes) to provide the methods to create and add new list elements. This makes that with the current interface for users of MainClass the first design is the simplest design and the best of the two.

However, it is possible to create a better design by decoupling MainClass and MiddleClass.

MainClass only needs to provide a method to add (already created) items to the list.

MiddleClass is actually a factory class, as already noted in the comments, and should be made available to the user to create the items that should be added to the list.

This way, MainClass doesn't need to be updated if new classes are added to the hierarchy, but only MiddleClass.


问:
The difference between *s.pd and s->pd
I was reading about copy constructors for structs and i found this example:

```<code>#include <iostream>
#include <string>
using namespace std;

struct SomeData {
    int * pd;
    string id;
    SomeData(SomeData & ref) {
        cout << "Copy Constructor called" << endl;
        pd = new int (*ref.pd);
        id = "Copy Constructed";
    }
    SomeData(string name) {
        pd = new int(0);
        id = name;
        cout << "Constructor for " << id << endl;
    };
    ~SomeData() {
        cout << "Destructor for " << id << endl;
        delete pd;
    }
};

int main() {
    SomeData s("First");
    *s.pd = 9;
    SomeData s2=s;
    cout << *s2.pd << endl;
    return 0;
}
</code>```

in the main, the member pd of SomeData is accessed using the dereference,
but why is that, isn't the correct way is

```<code>s->pd=9;
</code>```

why was it written like that in the example?

答:
This is an example of operator precedence not giving quite the results you expect. The example has the code

```<code>*s.pd = 9;
</code>```

which is equivalent to the following:

```<code>*(s.pd) = 9;
</code>```

You query why it isn't written as

```<code>s->pd = 9;
</code>```

but this is equivalent to

```<code>(*s).pd = 9;
</code>```

That is, the code in the example dereferences the value of pd that is a member of s, whereas the code you are asking about dereferences s (which is not legal as s is not a pointer and doesn't have an overload for the "->" operator).

This is because ".", the member selection operator binds more strongly than "*", the dereference operator.

See http://en.cppreference.com/w/cpp/language/operator_precedence for a complete list; "." has a precedence of 2, while "*" has a precedence of 3. Only "::" binds more strongly than ".".

Title: The difference between *s.pd and s->pd

Body:
This is an example of operator precedence not giving quite the results you expect. The example has the code

*s.pd = 9;

which is equivalent to the following:

*(s.pd) = 9;

You query why it isn't written as

s->pd = 9;

but this is equivalent to

(*s).pd = 9;

That is, the code in the example dereferences the value of pd that is a member of s, whereas the code you are asking about dereferences s (which is not legal as s is not a pointer and doesn't have an overload for the "->" operator).

This is because ".", the member selection operator binds more strongly than "*", the dereference operator.

See http://en.cppreference.com/w/cpp/language/operator_precedence for a complete list; "." has a precedence of 2, while "*" has a precedence of 3. Only "::" binds more strongly than ".".


问:
Inheritance is a null property in the parent a bad practice?
I am not a very experienced programmer. So I ask.

The field in question is the "Amount" field. I store an amount only in a couple levels of the derived class.

The code is a slice of the POCO classes that are making up my data model, the datalayer is Entity framework, code first.

I mention that because the reason I did the amount property like I did is because when I placed the Amount just in a derived class or two and not in the Navigation class, the table in the database would have an extra field for each class with an Amount property, like (Amount, Amount1, Amount2). I did not like that.

So after screwing around with the code for awhile I discovered that...

Placing the Amount property in the navigation class and overriding it in the classes that implemented Amount gave me a table with just one "Amount" field that was Null, unless it was one of the classes that used amount in which case it had a value, which was just what I wanted. I liked that.

So the question is, is the way the Amount property is handled completely proper or have some downside?

```<code>public class Navigation
{
    int Id { get; set; }
    string Title { get; set; }
    string Description { get; set; }
    ObservableCollection<Navigation> Children { get; set; }

    public virtual decimal? Amount
    {
        get { return null; }
        set { value = null; }
    }
}
public class C1 : Navigation { }
public class C2 : Navigation { }
public class C3 : Navigation
{
    private decimal _amount;
    public override decimal? Amount
    {
        get { return _amount; }
        set { if (value != null) _amount = (decimal)value; }
    }
}
public class C4 : Navigation
{
    private decimal _amount;
    public override decimal? Amount
    {
        get { return _amount; }
        set { if (value != null) _amount = (decimal)value; }
    }
}
</code>```

答:
One thing you can do if you want to add a property to only a few of the subclasses is to use another interface. In your example: Navigation -> AmountEnabledNavigation -> C3, but Navigation -> C1. In the code that handles the objects, e.g. adds the amounts, you can simply check if the object inherits from AmountEnabledNavigation and then decide based on that.

This also prevents later issues like exceptions when accessing the objects. Although these can be caught and handled, they slow down code considerably.


问:
Overriding methods by passing as argument the subclass object where the supertype is expected
I am just learning Java, and am not a practicing programmer.

The book I am following says that when overriding a method, the argument types must be the same, but the return types can be polymorphically compatible.

My question is why can't the arguments passed to the overriding method not be a subclass type of the super-type expected?

In the overloaded method, whatever method I call on the object is guaranteed to be defined on the object.

Notes on suggested duplicates:

The first suggestion appears to be about class hierarchy and where to put functionality.  My question is more focused on why the language restriction exists.

The second suggestion explains how to do what I'm asking, but not why it has to be done that way.  My question is focused on the why.

答:
The concept you initially refer to in your question is called covariant return types.

Covariant return types work because a method is supposed to return an object of certain type and overriding methods may actually return a subclass of it. Based on the subtyping rules of a language like Java, if S is a subtype of T, then wherever T appears we can pass an S.

As such it is safe to return an S when overriding a method that expected a T.

Your suggestion to accept that an overriding a method uses arguments that are subtypes of those requested by the overridden method is much more complicated since it leads to unsoundness in the type system.

By one hand, by the same subtyping rules mentioned above, most likely it already works for what you want to do. For instance

```<code>interface Hunter {
   public void hunt(Animal animal);
}
</code>```

Nothing prevents implementations of this class from receiving any kind of animal, as such it already satisfies the criteria in your question.

But let's suppose we could override this method as you suggested:

```<code>class MammutHunter implements Hunter {
  @Override
  public void hunt(Mammut animal) {
  }
}
</code>```

Here's the funny part, now you could do this:

```<code>AnimalHunter hunter = new MammutHunter();
hunter.hunt(new Bear()); //Uh oh
</code>```

As per the public interface of AnimalHunter you should be able to hunt any animal, but as per your implementation of MammutHunter you only accept Mammut objects. Therefore the overriden method does not satisfy the public interface. We just broke the soundness of the type system here.

You can implement what you want by using generics.

```<code>interface AnimalHunter<T extends Animal> {
   void hunt(T animal);
}
</code>```

Then you could define your MammutHunter

```<code>class MammutHunter implements AnimalHunter<Mammut> {
   void hunt(Mammut m){
   }
}
</code>```

And using generic covariance and contravariance you can relax the rules in your favor when necessary. For instance we could make sure that a mammal hunter can only hunt felines in a given context:

```<code>AnimalHunter<? super Feline> hunter = new MammalHunter();
hunter.hunt(new Lion());
hunter.hunt(new Puma());
</code>```

Supposing MammalHunter implements AnimalHunter<Mammal>.

In that case this would not be accepted:

```<code>hunter.hunt(new Mammut()):
</code>```

Even when mammuts are mammals it would not be accepted due to the restrictions on the contravariant type we are using here. So, you can still excercice some controll over the types to do things like the ones you mentioned.

Body:
The concept you initially refer to in your question is called covariant return types.

Covariant return types work because a method is supposed to return an object of certain type and overriding methods may actually return a subclass of it. Based on the subtyping rules of a language like Java, if S is a subtype of T, then wherever T appears we can pass an S.

As such it is safe to return an S when overriding a method that expected a T.

Your suggestion to accept that an overriding a method uses arguments that are subtypes of those requested by the overridden method is much more complicated since it leads to unsoundness in the type system.

By one hand, by the same subtyping rules mentioned above, most likely it already works for what you want to do. For instance

interface Hunter {
   public void hunt(Animal animal);
}

Nothing prevents implementations of this class from receiving any kind of animal, as such it already satisfies the criteria in your question.

But let's suppose we could override this method as you suggested:

class MammutHunter implements Hunter {
  @Override
  public void hunt(Mammut animal) {
  }
}

Here's the funny part, now you could do this:

AnimalHunter hunter = new MammutHunter();
hunter.hunt(new Bear()); //Uh oh

As per the public interface of AnimalHunter you should be able to hunt any animal, but as per your implementation of MammutHunter you only accept Mammut objects. Therefore the overriden method does not satisfy the public interface. We just broke the soundness of the type system here.

You can implement what you want by using generics.

interface AnimalHunter<T extends Animal> {
   void hunt(T animal);
}

Then you could define your MammutHunter

class MammutHunter implements AnimalHunter<Mammut> {
   void hunt(Mammut m){
   }
}

And using generic covariance and contravariance you can relax the rules in your favor when necessary. For instance we could make sure that a mammal hunter can only hunt felines in a given context:

AnimalHunter<? super Feline> hunter = new MammalHunter();
hunter.hunt(new Lion());
hunter.hunt(new Puma());

Supposing MammalHunter implements AnimalHunter<Mammal>.

In that case this would not be accepted:

hunter.hunt(new Mammut()):

Even when mammuts are mammals it would not be accepted due to the restrictions on the contravariant type we are using here. So, you can still excercice some controll over the types to do things like the ones you mentioned.


问:
Actors in a sequential protocol handshake
I am new to actors and trying to implement a very sequential protocol handshake (over websockets). This is in Scala/Akka.

It goes something like this:

HTTPs connection is established then upgraded to websocket

Client says HELLO

Server responds HELLO

Client says I want to use subprotocol X or Y

Server says I support Y and will start using it

Client starts talking using subprotocol Y

My question is one of proper practice on the server side. Should I have a single actor for the connection, that is updated with the state of the handshake (for example, with a sequence like CONNECTED->RECEIVED_HELLO->RECEIVED_OFFER->BEGIN_SUBPROTOCOL->..(do work)..->CLOSE_CONNECTION) using messages-to-self & ask?

Or is there a better pattern for such a serial/synchronous protocol initialization?

答:
First off, check out akka.io. It provides actor-based processing for your input and output needs. There are a number of good examples of creating servers using akka.io that are well worth your while to study.

To answer part of your question ...

You would create an actor whose sole responsibility is to set up and maintain the connection. It would receive the HELLO messages and respond appropriately until everyone was satisfied. Your actual server sits downstream from this actor; it only needs to know that the protocol was satisfied and a connection established, and it can send and receive data.

By separating protocol concerns from serving concerns, your first actor has only a single responsibility. You can then substitute any other actor to implement that protocol, or even implement a new protocol, without affecting your server one iota.


问:
To cache or not to cache a ReadOnlyWrapper object?
I have a system with a structure like this:

The ConcreteWriteable is caching the ReadOnlyWrapper.

This is a similar system to what .Net's System.Array uses for its Array.AsReadOnly<T>(T[] array) method (ignoring for the moment that System.Array's AsReadOnly is static). However looking at the code for System.Array at reference source, System.Array.AsReadOnly is returning a new wrapper each time, whereas I'm creating the wrapper at the same time as the ConcreteWriteable and caching it, then returning the same one each time.

This got me thinking, is there some reason why I shouldn't be doing this? Is there some reason why creating a new wrapper each time is more desirable than returning the same wrapper (bearing in mind that the wrapper cannot possibly change the ConcreteWriteable and is indeed a wrapper, not a copy)?

答:
If the wrapper is truly immutable, program behavior is identical whether you create a new wrapper each time, or reuse one. The only difference is the thrashing of the garbage collector.

I have thought about using structs as read-only collection wrappers, instead of class instances, but I realized there would be little gain, since often a collection is cast as a collection interface, which would box the structure.


问:
What are the benefits of using Dependency Injection and IoC Containers?
I'm planning to do a talk on Dependency Injection and IoC Containers, and I'm looking for some good arguments for using it.

What are the most important benefits of using this technique, and these tools?

答:
I think the actual benefits are more political than technical. DI is simply an alternative to the Service Locator pattern, nothing more. By itself, it does not make it easier to follow principles like SRP or OCP, or to decouple layers. Other respondents here are confusing different concepts and techniques, IMO.

You can achieve the same goals with respect to high cohesion and low coupling by using Service Locators, or by simply instantiating dependencies directly whenever applicable (which is most of the time).

Now, I know many will disagree with this opinion. I will be glad to discuss concrete examples.

ContentLicense: CC BY-SA 2.5


问:
Why does the new ADT create a static inner class Fragment by default?
Honestly, I can't help but feel that this is done merely to confuse newcomers. Most of the errors on Stack Overflow by complete Android newbies mostly stem from that they have a static inner class Fragment that they don't understand how it works, why it's there, and try to use Activities even though they don't fully understand the concept behind what is happening.

I must admit, I had trouble understanding the "PlaceholderFragment" approach too, and using static inner classes isn't really extensible at all. The first thing you'd have to do is create an actual class outside - but why do newbies have to do that?

I think this could be much more efficient if they used a project structure similar to the following simple fragment-based android project structure:

src

wholepackagename

activity

MainActivity

fragment

FirstFragment

SecondFragment

res

layout

values

...

With the code of

src/wholepackagename/activity/MainActivity:

```<code>public class MainActivity extends FragmentActivity implements FirstFragment.Callback
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
        {
            public void onBackStackChanged()
            {
                int backCount = getSupportFragmentManager().getBackStackEntryCount();
                if (backCount == 0)
                {
                    finish();
                }
            }
        });

        if (savedInstanceState == null)
        {
            getSupportFragmentManager().beginTransaction().add(R.id.main_container, new FirstFragment()).addToBackStack(null).commit();
        }
    }

    @Override
    public void firstFragmentCallback()
    {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_container, new SecondFragment()).addToBackStack(null).commit();
    }
}
</code>```

src/wholepackagename/fragment/FirstFragment.java:

```<code>public class FirstFragment extends Fragment implements View.OnClickListener
{
    private Callback callback;

    private Button firstFragmentButton;

    public static interface Callback
    {
        void firstFragmentCallback();
    }

    public FirstFragment()
    {
        super();
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
        try
        {
            callback = (Callback) activity;
        }
        catch (ClassCastException e)
        {
            Log.e(getClass().getSimpleName(), activity.getClass().getSimpleName() + " must implement Callback interface!", e);
            throw e;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_first, container, false);
        firstFragmentButton = (Button) rootView.findViewById(R.id.fragment_first_button);
        firstFragmentButton.setOnClickListener(this);
        return rootView;
    }

    @Override
    public void onClick(View v)
    {
        if(v == firstFragmentButton)
        {
            callback.firstFragmentCallback();
        }
    };
}
</code>```

src/wholepackagename/fragment/SecondFragment.java:

```<code>public class SecondFragment extends Fragment implements View.OnClickListener
{
    private Button secondFragmentButton;

    public SecondFragment()
    {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_second, container, false);
        secondFragmentButton = (Button) rootView.findViewById(R.id.fragment_second_button);
        secondFragmentButton.setOnClickListener(this);
        return rootView;
    }

    @Override
    public void onClick(View v)
    {
        if(v == secondFragmentButton)
        {
            Toast.makeText(getActivity(), "This is an example!", Toast.LENGTH_LONG).show();
        }
    };
}
</code>```

Android-Manifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="wholepackagename"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="wholepackagename.activity.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

res/layout/activity_main.xml:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

res/layout/fragment_first.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/fragment_first_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/first_button" />

</RelativeLayout>
</code>```

res/layout/fragment_second.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/fragment_second_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/second_button" />

</RelativeLayout>
</code>```

res/values/strings.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Application name</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="first_button">First Button</string>
    <string name="second_button">Second Button</string>
</resources>
</code>```

To me, it seems that the static inner class Fragment doesn't really support any kind of maintainability, it's hard to see what is going on, and the overall functionality is not obvious as the Activity and Fragment (display of fragment and logic) are mixed together, which makes it hard to see and oversee for a newbie.

I believe it would provide an easier entry into developing for the Android platform to have an example like above. Are there any benefits to the current approach, providing a static inner class as a Fragment?

答:
I, and others, share your sentiment that Fragments are pretty weird and should not be blindly accepted as Good Things™.

I always thought the intention behind their existence in the bootstrap code was to throw Fragments in front of developers' faces as early as possible. Since Fragments have not been around since version 1, I imagine Google felt they needed to put some weight behind their introduction in order to get more people on board. But, I can only speculate.


答:
Is checking return values always required?

I don't think so; rather, they are almost always required. Proper error checking is very important, although sometimes it can admittedly be a pain in the neck.

However, your particular example does not describe a typical "perform operation that may fail and check the error" scenario. If your assumption about the sum of squares being positive is right (e. g. you expect this to be the case, and you don't permit e. g. NaN inputs), then what you are looking for is an assertion.

Assertions are used in situations exactly like this: when you have an operation that can sometimes fail, but you always pass it inputs for which it cannot possibly/shouldn't ever fail. Your program's internal consistency depends on this, so you assert, so that if this promise/assumption in your code ever breaks, you will get notified (i. e. the program crashes reliably at the earliest point it detects the inconsistency).

Body:
We know that checking return values prevent our software from unexpected states. (You can see CWE definition.)
But, we are sometimes sure about the return value. For example:

```<code>bool calculateSquareRootReturnFalseIfInputIsNegative(float input, float& output);
float calculateHypotenuse(float a, float b){
  float c2 = (a*a) + (b*b);
  float c;
  calculateSquareRootReturnFalseIfInputIsNegative(c2, c);
  return c;
}
</code>```

The local variable c2 is always positive. So, calculateSquareRootReturnFalseIfInputIsNegative() always returns true. I shouldn't check its return value.

Finally, Is "check all return values not already known by caller" a valid idiom?

Thanks..


问:
Refactoring: When to add a new class in the project?
When do you feel that you need a new class (maybe when you are developing or after development for refactoring purpose)?

Maybe I can start from my existing variables and think how I can reorganize them into some classes! Please add more!

答:
Using classes make your program shorter and more clear (Actually if the program is not too simple). Classes can encapsulate some of your existing variables and the related methods. Each class represents a concept which in turn makes finding and understanding of the solution easier.

To clarify these I give an example:

1- Suppose a program which takes the dimensions of a rectangle and calculate its area,
it could be:

```<code>static void Main()
{
    int w,h;
    read(w,h);
    int a = calcArea(w,h); // it simply returns w x h
    print(a);
}
</code>```

2- A program which takes three rectangles in different coordinates and prints the intersect area of them, the old approach gives you

```<code>static void Main()
{
    int x1,y1,w1,h1,x2,y2,w2,h2,x3,y3,w3,h3; // for rectangles
    int x4,y4,w4,h4;  // for the intersect
    calcIntersect(x1,y1,w1,h1,x2,y2,w2,h2,x3,y3,w3,h3,x4,y4,w4,h4);
}
void calcIntersect(int x1,int y1,int w1,int h1,int x2,
 int y2,int w2,int h2,int x3,int y3,int w3,int h3,
 int& x4,int& y4,int& w4,int& h4)
{
   // a fancy algorithms which works with this bunch of dimensions, its scary!!
}
</code>```

As you have multiple objects the need for class is felt, then you would have:

```<code>class Rectangle
{
    public int x,y,w,h;
}
// in your main
static void Main()
{
    Rectangle r1,r2,r3, r4; //r4 for intersect
}
</code>```

Now instead of thinking of dimensions think of rectangles as a new concept!...., I can calculate the intersect of two rectangles which is itself a rectangle and the same procedure gives me the intersect of this rectangle with the third one. You observe that this new concept makes finding the solution easier.

```<code>class Rectangle
{
    public int x,y,w,h;
    Rectangle Intersect(Rectangle r)
    {
       // now the situation is much better
    }
}
static void Main()
{
    Rectangle r1,r2,r3,r4;
    Rectangle temp = r1.Intersect(r2);
    r4 = r3.Intersect(temp);
}
</code>```

Body:
Using classes make your program shorter and more clear (Actually if the program is not too simple). Classes can encapsulate some of your existing variables and the related methods. Each class represents a concept which in turn makes finding and understanding of the solution easier.

To clarify these I give an example:

1- Suppose a program which takes the dimensions of a rectangle and calculate its area,
it could be:

static void Main()
{
    int w,h;
    read(w,h);
    int a = calcArea(w,h); // it simply returns w x h
    print(a);
}

2- A program which takes three rectangles in different coordinates and prints the intersect area of them, the old approach gives you

static void Main()
{
    int x1,y1,w1,h1,x2,y2,w2,h2,x3,y3,w3,h3; // for rectangles
    int x4,y4,w4,h4;  // for the intersect
    calcIntersect(x1,y1,w1,h1,x2,y2,w2,h2,x3,y3,w3,h3,x4,y4,w4,h4);
}
void calcIntersect(int x1,int y1,int w1,int h1,int x2,
 int y2,int w2,int h2,int x3,int y3,int w3,int h3,
 int& x4,int& y4,int& w4,int& h4)
{
   // a fancy algorithms which works with this bunch of dimensions, its scary!!
}

As you have multiple objects the need for class is felt, then you would have:

class Rectangle
{
    public int x,y,w,h;
}
// in your main
static void Main()
{
    Rectangle r1,r2,r3, r4; //r4 for intersect
}

Now instead of thinking of dimensions think of rectangles as a new concept!...., I can calculate the intersect of two rectangles which is itself a rectangle and the same procedure gives me the intersect of this rectangle with the third one. You observe that this new concept makes finding the solution easier.

class Rectangle
{
    public int x,y,w,h;
    Rectangle Intersect(Rectangle r)
    {
       // now the situation is much better
    }
}
static void Main()
{
    Rectangle r1,r2,r3,r4;
    Rectangle temp = r1.Intersect(r2);
    r4 = r3.Intersect(temp);
}


答:
No. There is nothing idiomatic about error-handling-by-return-value, either in the callee side or the caller. Leave these terrible practices in the Stone Age where they belong.

You should write your functions to throw on failure. If you're using a library that hasn't been updated since 1972, then you need to wrap it to provide a usable interface.

Title: Is checking return values always required?


问:
How to get out of the support rut and start repaying the technical debt!
I have a "friend". Yes good start I know but honestly this isn't me!

Basically he's been working on a successful project for about 4 years now, the difficulty is the technical debt has caught up and he's finding it almost impossible to stop supporting the product (tweaking this and that) and actually move on with real development.

I've made various suggestions, log all of your time, create tickets, don't answer emails etc etc. The problem with this is that it seems to only serve as a reminder that he's not getting anything "useful" done.

The technical debt has largely occurred because in the first instance it was a big benefit to the product, to take requests and phone calls from users and just quickly implement them.

What I would like to know is does anybody have any suggestions for how he might get out of this rut, a large part of which would be changing the perceptions of the users so that they don't think they can just ring and expect something to be done then and there.

It's all very well saying plan better, though I understand it's very difficult to plan actual development given the requirement for support and the relative pressures from users (see above).

答: The key is what kind of development methodology does he have around him to shield him to some degree?  For example, in Scrum there is the idea that what work will be done doesn't change during the sprint usually.  Thus there is some rules about what is going to be done and what may not be done right away.  The other question is to what extent does management support his wanting to not be in a support rut?  This is could also be important as an apathetic management can be a bit of a death knell for your friend's project.</p>


答:
In OOA&D I would like to know how you easily distinguish if a class is non-static?

Why? In OO, static classes should be very rare (if your language allows them at all). Your IDE will quickly tell you that there is no constructor for that class, and if not your IDE, the compiler surely will.

But for the one who is used to procedural programming how he can think of classes and the necessity for objects?

Practice. Objects aren't a necessity. But getting into the train of thought to look at problems from a "what bundles of data/behavior make up this problem?" perspective rather than a "what steps do I need to take to solve this problem?" perspective takes time and practice.

Objects also have state and are mutable.

No.

In modern OO design, objects very often are not mutable. They more often have state, but even that is not a good rule of thumb for making objects. Many of the OO design patterns (strategy, most factories, some visitors, etc.) will use objects that contain no state.

I would like some rules of thumb or a short definition to easily distinguish classes in any project.

There are no universal rules of thumb. Are there rules of thumb for what functions to make in procedural programming? No, it will vary based on what problem you face, the language you're using and your particular coding style. Even skilled programmers will often disagree about where the lines should be drawn to split up classes.

Title: Refactoring: When to add a new class in the project?

Body:
When do you feel that you need a new class (maybe when you are developing or after development for refactoring purpose)?

Maybe I can start from my existing variables and think how I can reorganize them into some classes! Please add more!


答:
Simple: static classes are exceedingly dumb. If you think you have identified a case for a static class, then stop- because you haven't. You may have identified a namespace.

There are no static classes in OOP.


问:
What kind of user info is ok to be stored as plain text in SQL Database?
I'm practicing around building e-commerce asp.net applications that allows for users to register to the site and their user credentials are stored in a MySQL database. In my sample project the registration asks for the users username, password, full name, phone #, email, home address (for shipping of products purposes).

I know its good practice to store the user's password as a salted hash.  But is there any other info that should be stored the same way or not?  For example should the username also be stored as a salted hash or even encrypted?

I guess I'm just wondering what kinds of information is it ok to be stored in plain text in MySQL database for an asp.net web app? And which items are recommended to be stored in a salted hash? And which items should be stored using encryption?

答:
I guess I'm just wondering what kinds of information is it ok to be stored in plain text in MySQL database for an asp.net web app?

What information would you be okay with being readily available to anyone, even those with malicious intent?

My email address for example is not okay to be publicly visible, even if nobody knows it's me. If you are running something like a porn site, then I probably don't want people to know that my name (or even address) is stored in your database.

If you're not showing this information to other users of the site, assume that it is private information, and your responsibility to protect.


问:
Passing by argument vs keeping it as a member
I really cannot decide what option is the best, I see plenty of down/upsides to both approaches and right now I'm undecided.

For example;

```<code>class DX11GBuffer
{
public:
    DX11GBuffer(ID3D11DevicePtr device, ID3D11DeviceContextPtr context, D3D11_TEXTURE2D_DESC backbufferTextureDesc);
    ~DX11GBuffer();

    void BindForGeometryStage(ID3D11DepthStencilViewPtr dsv);
    // ...
}
</code>```

"dsv" is not owned by the object and thus passed every frame, but it could just aswell be passed as a argument in the constructor and stored seeing as it is a smart pointer.

I guess what I am getting at is I understand there are pitfalls for keeping too much state in an object but also passing so much as function arguments means a whole lot of ASCII. Likewise defining "argument objects", collection of data for functions, seems to add alot of overhead aswell if it is to be applied everywhere as a rule of thumb.

I guess I am looking some general guidelines on when to pass as argument vs when to store as member.

答:
Member variables are variables are a "has a" relationship (the rectangle has a width). If the object does not have the variable then it should be passed into it to be used where required, if it's related to the object itself then it should be stored in the object.

A quick way to test the relation could be seeing how much that object uses the variable. If you use it in just one unit of code, leave it as it is (being passed in) however if multiple functions within that object make use of it then storing it as a member variable would probably make more sense.


问:
Design solution for communicating between multiple layers
We are developing a framework that has several layers and would be deployed in a multi-threaded environment. Each layer may have its own input/output data type. The top layer takes the input, performs some actions on the data and passes it to the next layer. Based on the output from next layer, the top layer would perform another set of operations on the data. Similar interactions happen between other layers.

There are two use cases that we did not incorporate in the original design:

Generating metrics over what operations each layer performs on the data.

The change in data in one layer affects the operations in another layer, the changes should be recorded and each layer should have capability to fetch the list of changes.

After some thinking we came up with two approaches to accommodate these requirements in the existing design:

Use observer pattern and let each layer report its changes. These changes can be then pulled by the layer that needs to use it.

Pros:

Since we have already come up with a design for the framework and most of work is complete. This approach would not require significant changes to the existing design, if any.

Cons:

It becomes difficult to manage(record and report back) changes corresponding to each layer.

There is a central class that aggregates all the data for each request. This class acts like a global variable. It has to be initialized and deleted by the top layer. Adding another top layer could be error prone.

Extend the current data classes using an interface equivalent to EventContainer. This way all the layers would record their changes and spit them in their output.

Pros:

This approach is much more cleaner and extendable than observer pattern.

Cons:

It would require significant design changes.

The concept of data having events as well merges two separate concerns into one and does not seem like a good idea.

We would like to know if there is a design pattern or any other solution that solves this problem?

Which of the above two solutions should be given higher preference considering that we would want a flexible, extendable and cleaner solution?

答:
We would like to know if there is a design pattern or any other
  solution that solves this problem?

To me this sound like the kind of problem that Enterprise Integration Patterns solve by using communication channels and message passing.

The patterns can be use to decouple the communication between applications, between layers or between components.

There is a number of frameworks that can be used to implement this type of applications like Spring Integration, Apache Camel and Mule

What you describe sounds to me like a Service Activator. One of many different types of message endpoints (ME). The communication between your components will happen through message channels.

The components/service activators are totally unaware of each other and the channels define the pipeline that carries the messages between them.

Most frameworks, like Spring Integration, provide you with interceptors to get a chance to do something with the messages as they flow through the pipeline (equivalent to your observer pattern).

Interesting metrics can also be captured in the form of MXBeans as the message flow through the pipeline.

+----+    channel    +----+    channel    +----+
|    |---------------|    |---------------|    |
| ME |  <-message->  | ME |  <-message->  | ME |
|    |---------------|    |---------------|    |
*----+               +----+               +----+

In this type of frameworks the channel abstraction gives you a lot of power. The channel could be direct channels or publish subscribe channels, and the hand off of message can be synchronous or asynchronous. So you have total control of the message flow, the span of transactions, etc.


问:
How many Angular Controllers and/or Directives is too many?
I'm building a large, editable data table with angular, and I'm trying to figure out what the best practice is.

The table will be a couple of hundred rows, with a couple of dozen columns, so upwards of 2000 cells. Each cell needs to be editable inline.

My first thought was to have directives at the cell level, so it would look something like:

```<code><editablecell model="some model expression"></editablecell>
</code>```

But I'm concerned about the performance of creating thousands of directives instances, each with its own scope, controller, and event listeners. I'm worried that if the table needs to be redrawn (you change the sorting, for instance) the performance will suffer.

Is it a better idea to maybe have a per-row directive that has a meatier controller and template to handle all the data binding and event handling at a higher level, and thus create fewer child scopes and event listeners?

答:
I wouldn't worry too much about the number of directives and controllers, at least not without performance data. Proper use of directives and controllers is what makes your page maintainable. It's about coming up with a re-usable set of components that you can mix and match.

The number of watchers can be problematic as it means that every digest cycle all those watchers will fire off. How much of the data is dynamic and how much is static?

For static data, Angular 1.3 added one-time bindings which can help you reduce the number of watchers. You can read about those here. If you're dealing with thousands of rows of dynamic data, I'm not sure there's really much you can do to optimize that. It simply takes a lot of time to update thousands of pieces of information. There may be some optimizations you can make with more information about the subjective case you're working on.

OwnerDisplayName: alexp


答:
I have no concrete suggestions, but I do have some questions which might help clarify the situation.

What needs to be captured?

Just the final (current) data state; i.e. just about the results, not about the processes.

Snapshots of the data states at various time points.

An abridged description of the processes that were applied.
"abridged" as in: trimmed-down, summarized; as opposed to the "perfect capture" described next.

A perfect capture of the parameters of every single process that has ever happened;
"perfect" as in enabling a perfect "record-replay" of all data transformations at a later time;
as in data provenance in scientific data management.

What is the overall paradigm of the system?

This question is not about the programming languages or coding style; it asks about the manner in which data changes are propagated throughout the system.

Imperative / command-and-control

Event-based / rule-based / triggered / logic / reactive

Pull-based / functional / Lazy-evaluation  / on-demand

Goal-based / optimizational / algorithmic

Imperative

Sample description: An upper-echelon (boss) class sends one or more processing commands to a number of lower-echelon (subordinate) classes. Each lower-echelon class breaks down the command it received, and sends those sub-commands to some lower-level peons (workers) for processing.

Event-based

Sample description: A number of triggering conditions are registered: "if THIS happens then do THAT". Whenever the data is changed, the triggering conditions are checked; if there are any matches, the registered actions are performed. After the registered actions are performed, more triggers could be activated, resulting in a chain-reaction.

Pull-based

In the beginning, all that is defined is a set of placeholders (identifiers) for every piece of data, along with black boxes that transform some pieces of data into some other pieces of data.

The final (ultimate) consumer of a piece of data makes the request to the system. The system checks to see if that data is available; if it is not, it searches for the black boxes that would be able to produce that data. Once one is found, it looks at whether the black box has all of the prerequisite data to start running. If it doesn't, the system tries to search again for upstream black boxes that would prepare those missing prerequisites. Ultimately, the search would hit some pre-existing data in the datastore, and therefore the processing pipeline can be kick-started.

Goal-based

The user of the system specifies the desired goal-state or optimality metric, such as cost-functions to be minimized for, or other performance metrics to be measured on the data. The WHAT is specified; the HOW is not specified. That is, how the system reaches that goal (or, whether that goal is reachable or not) is not specified by the user. The system is supposed to solve that mystery somehow.

Such systems make heavy use of research in computer-science, algorithm and mathematical theory. These systems are highly specialized in the type of solutions they can search for.

Due to the nature of such systems, the current overall state is usually in plain view by every component inside the system. A wide variety of approaches (paradigms) are used in the implementation; all of the aforementioned paradigms (imperative; event-based; pull-based; algorithmic; iterative) can be used in combination to achieve the goal.

Title: Design solution for communicating between multiple layers

Body:
We are developing a framework that has several layers and would be deployed in a multi-threaded environment. Each layer may have its own input/output data type. The top layer takes the input, performs some actions on the data and passes it to the next layer. Based on the output from next layer, the top layer would perform another set of operations on the data. Similar interactions happen between other layers.

There are two use cases that we did not incorporate in the original design:

Generating metrics over what operations each layer performs on the data.

The change in data in one layer affects the operations in another layer, the changes should be recorded and each layer should have capability to fetch the list of changes.

After some thinking we came up with two approaches to accommodate these requirements in the existing design:

Use observer pattern and let each layer report its changes. These changes can be then pulled by the layer that needs to use it.

Pros:

Since we have already come up with a design for the framework and most of work is complete. This approach would not require significant changes to the existing design, if any.

Cons:

It becomes difficult to manage(record and report back) changes corresponding to each layer.

There is a central class that aggregates all the data for each request. This class acts like a global variable. It has to be initialized and deleted by the top layer. Adding another top layer could be error prone.

Extend the current data classes using an interface equivalent to EventContainer. This way all the layers would record their changes and spit them in their output.

Pros:

This approach is much more cleaner and extendable than observer pattern.

Cons:

It would require significant design changes.

The concept of data having events as well merges two separate concerns into one and does not seem like a good idea.

We would like to know if there is a design pattern or any other solution that solves this problem?

Which of the above two solutions should be given higher preference considering that we would want a flexible, extendable and cleaner solution?


问:
Scala and exception handling
I am curious why exception handling is a topic often ignored in Scala. Is it the goal of the language (or the style) to not rely on exception handling except for external input/code?

I was hoping the style guide had some discussion on exception checking/handling. Is there a good reference that I could consult to understand if there are any differences in handling exceptions in Scala vs. languages I'm more used to (C++/C#/Java/Ruby/etc)?

Would someone with some Scala years under their belt be willing to write down guidelines for exception handling that are Scala specific? or is the answer simply "do as you would in Java"? What is "the functional way"?

答:
Scala encourages the use of constructs like options and futures for error handling. First of all, lazy evaluation makes exceptions problematic, because there is a different stack when a function is executed than when it's queued to execute. Scala isn't lazy by default, but it can be lazy when you choose.

Also, options and futures are much more powerful than exceptions. You can chain operations on them, and they aren't limited to propagating straight up the stack like exceptions are. You can store them in collections and reduce duplication in handler code.

Pretty much the only time you use exceptions in Scala is for errors you can't handle that will kill your program anyway.

Title: Scala and exception handling


问:
The rule of 5 - to use it or not?
The rule of 3 (the rule of 5 in the new c++ standard) states :

If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

But, on the other hand, the Martin's "Clean Code" advises to remove all empty constructors and destructors (page 293, G12:Clutter) :

Of what use is a default constructor with no implementation? All it serves to do is clutter up the code with meaningless artifacts.

So, how to handle these two opposite opinions? Should empty constructors/destructors really be implemented?

Next example demonstrates exactly what I mean :

```<code>#include <iostream>
#include <memory>

struct A
{
    A( const int value ) : v( new int( value ) ) {}
    ~A(){}
    A( const A & other ) : v( new int( *other.v ) ) {}
    A& operator=( const A & other )
    {
        v.reset( new int( *other.v ) );
        return *this;
    }

    std::auto_ptr< int > v;
};
int main()
{
    const A a( 55 );
    std::cout<< "a value = " << *a.v << std::endl;
    A b(a);
    std::cout<< "b value = " << *b.v << std::endl;
    const A c(11);
    std::cout<< "c value = " << *c.v << std::endl;
    b = c;
    std::cout<< "b new value = " << *b.v << std::endl;
}
</code>```

Compiles fine using g++ 4.6.1 with :

```<code>g++ -std=c++0x -Wall -Wextra -pedantic example.cpp
</code>```

The destructor for struct A is empty, and not really needed. So, should it be there, or should it be removed?

答:
I prefer a different phrasing of the rule of three, which seems more reasonable, which is "if your class needs a destructor (other than an empty virtual destructor) it probably also needs a copy constructor and assignment operator."

Specifying it as a one way relationship from the destructor makes a few things clearer:

It doesn't apply in cases where you provide a non-default copy constructor or assignment operator as an optimization only.

The reason for the rule is that the default copy constructor or assignment operator can screw up manual resource management. If you're manually managing resources, you're likely to have realized that you'll need a destructor to release them.

Title: The rule of 5 - to use it or not?


答:
Make someone else take the calls, and have the line change from

We'll get to that right away.

to

Very good suggestion. I'll create a feature request to begin work on it as soon as possible. If you'd like to follow the progress on your request, you can track it here: [link to case tracker ticket]. In the future, you can also submit requests for futures in the same way as I am here: [link to case tracker]

That's probably the simplest and most effective way to do it in my opinion. The last bit tries to reduce the stress on this person answering the calls over time.

The problem you're seeing with the current 'priority' system is that when everything is a priority, nothing is a priority. For that, your friend desperately needs to heed the advice of @Larry Coleman - people separate from development that manage change requests. Ideally your friend shouldn't even know about a feature request, until that separate group agreed that it should be prioritized for work. That could even be this new person who's answering the calls now that prioritizes them - as long as they understand the business, and understand the development.

Title: How to get out of the support rut and start repaying the technical debt!

Body:
I have a "friend". Yes good start I know but honestly this isn't me!

Basically he's been working on a successful project for about 4 years now, the difficulty is the technical debt has caught up and he's finding it almost impossible to stop supporting the product (tweaking this and that) and actually move on with real development.

I've made various suggestions, log all of your time, create tickets, don't answer emails etc etc. The problem with this is that it seems to only serve as a reminder that he's not getting anything "useful" done.

The technical debt has largely occurred because in the first instance it was a big benefit to the product, to take requests and phone calls from users and just quickly implement them.

What I would like to know is does anybody have any suggestions for how he might get out of this rut, a large part of which would be changing the perceptions of the users so that they don't think they can just ring and expect something to be done then and there.

It's all very well saying plan better, though I understand it's very difficult to plan actual development given the requirement for support and the relative pressures from users (see above).


问:
excute Vs excuteOnExecutor
There are two ways to execute AsynTask, i.e., execute and executeOnExecutor. I already know that execute works serially and executeOnExecutor works in parallel. So my question is:

Which one to use?

Which one is better?

Can someone help me understand which one to use in which situation?

答:
On recent versions of android, "execute" will cause your task to be put into a queue from which a single background thread will pick it up and execute it; as you say, such tasks are executed serially (although you should not rely on this, as older versions of android started one thread for each task).

executeOnExecutor, however, gives you more control, because you can use any object that implements the Executor interface to execute the task. Even if you only limit yourself to the standard ThreadPoolExecutor implementation, this means you can take control of:

the maximum number of tasks that can be executed simultaneously

the type and parameters of queue used (e.g. whether the queue is bounded or unbounded)

the behavior when a new task is submitted while the queue is full

For most purposes, execute is adequate, but you would use executeOnExecutor when you need more control, either because a single thread isn't enough, or because you need to guarantee you only get one thread when using older versions of android, or because you have an unusual requirement on how submitted tasks are handled.

Title: excute Vs excuteOnExecutor


问:
Does dynamically generating classes in python affect readability/performance?
I have a set of classes that represent different objects (tables in a database):

```<code>class ObjA:
    # some class specific attributes and methods

    def refresh(self):
        # implementation
        pass

class ObjB:
    # some class specific attributes and methods

    def refresh(self):
        # implementation
        pass
</code>```

and they all have a refresh method. Now I have a task manager (like Luigi) that is used to call the refresh method on each class and the definitions look like:

```<code>from somewhere import ObjA, ObjB

class RefreshObjA(TaskManager):
    def run(self):
        ObjA.refresh()

class RefreshObjB(TaskManager):
    def run(self):
        ObjB.refresh()
</code>```

TaskManager here is a parent class provided by the manager module. As you can see, the class definitions all have an identical pattern and naming convention, and it stands to reason that these can be dynamically generated as generateRefreshClasses([ObjA, ObjB, ...]).

However, I have been resisting this and writing each one out explicitly because

All the information re: the classes is available when the code is written i.e. I'm not reliant on any external/user generated input which is probably where dynamic generation is useful. This use is purely to save space/keystrokes/repetition.

One doesn't know if some ObjX might need modifications/additional requirements and will need to be careful to remove it from the dynamic generator, lest it is overwritten.

It is harder to reason where (as in file and line no:) an execution error occurs if the code is dynamically generated.

These classes might be imported elsewhere in the code base and I lose out on the static inspection based checking provided by the IDE.

Are these valid reasons to continue to individually define the classes (there might be about 20 or so of them) or are there other benefits to dynamic generation that might make these concerns small in comparison? Would dynamic generation of classes be considered acceptable/good practice in such an application?

答:
You seem to have an appreciation of the trade-offs involved here. As you say, since you know all the information about your classes in advance, it doesn't quite make sense to generate them dynamically.

One alternative to reduce your boring duplicated boilerplate code is to use Python's wonderful support for metaprogramming. If all your refresh methods follow a similar template but the details vary due to the names and types of your classes' attributes, it makes sense to use a metaclass to generate this method when the class is created. In other words, you keep your class statements, and you still declare your class members statically in code, but the information about the refresh boilerplate is kept in one place (in the template that is used by the metaclass). (You could get the same effect using a regular base class and introspection; without more details about your code, I can't give you a clear assessment of what approach would be a good fit for your problem.)

A second option would be to use a code generator. This typically takes the form of a script which takes (for example) some XML or YAML defining your objects as input, and writes out a valid Python file into your build directory. Don't check the generated code into source control; instead just run the generator script every time you build the code. This way you still get file/line information when debugging, and the resulting code is typically not too hard to understand because it's mostly boilerplate. On the other hand, you can't directly edit the file once you've diagnosed a problem because it'll be overwritten next time you run a build - you have to modify the generator. So this approach still has many of the advantages and disadvantages of full-blown runtime class creation.

Another question you should consider asking is "Do we really know everything about these objects in advance?". 20 similar classes is a lot, and it suggests to me that a future requirements change may in fact need you to load these classes at runtime. While you should of course follow YAGNI, you can still design your code in such a way that this change would be easy to make in future. This is another way in which metaprogramming can help you out.


答:
Primary reason to use a class is that there is a concept in domain you are trying to express in your code and you want to codify this concept in some way. Usually, classes are created when you, as a developer, see, through your years of experience, that there is a concept in what you are trying to achieve and you want to explicitly convert this concept into code.

But also, many of the concept show up after you have written the code, quite often as various code smells. There are two examples :

Multiple values being passed around together.

Be it Point or Customer, you can sometimes see that there are multiple (3+) variable all being passes around together. Code usually needs all, or most of those variables and even if it doesn't directly need them, it's dependencies might do. This is great opportunity to introduce a class to encapsulate all those variables. After that, you realize that many of the functions that work on those fields could actually be part of the class itself. And then, you might realize this is a concept within your domain, that you missed when doing analysis or design.

Big functions

It happened multiple times to me, that I found a function that was just too long. But when I tried to divide it into smaller functions, it resulted in all of the function's state being passed around in parameters. This is great opportunity to introduce a class to represent the whole function itself. The function's parameters might become a classe's constructor. The function's variables become fields. And then, you can easily separate the big function into smaller ones, because they all use shared state instead of relying on parameter passing. And then, you realize some of the ifs and switches might be represented as subclasses instead of code flow constructs, creating rich, maintainable and expressive representation instead of one huge hard-to follow and maintain function. This should make you think : if this piece of code was so complex, shouldn't it be some kind of concept in domain I'm working in?

Classes as "structures with functions"

You are saying you have experience with procedural programming. Then you must know about structures and their use cases. Structures and classes overlap in many of those use cases. Some people even say that classes are just structures with functions bolted onto them and that they are no different than procedural programming. While I disagree, it might be good way for you to start thinking about classes. So whenever you would create a structure, you instead create a non-static class. The rest then follows.

Transparent dependencies and control flow

Another problem with static classes is that of dependency. If method of a class is static, then it becomes hard to tell what code actually uses this method. It becomes even worse problem if static state (in form of static fields) is involved. It becomes extremely hard to follow the flow of a code when you don't know what other methods might be involved. If you use non-static classes, it becomes much cleaner, because you know what piece of memory method can modify, instead of working with global state. Actually, global state is the keyword here. It is generally known problems with global state range from pain in the ass to total nightmare. You should be striving to minimize amount of global state in your programs. Usage of non-static classes should be prioritized over static classes whenever possible.


答:
Passwords must be stored hashed always, and make sure they are never logged, for example by query loggers. Hashing is important as opposed to encryption, because it should be a one-way, nonreversible process.

Secret questions to help recover passwords are good to encrypt. As these are secret, and they themselves can reveal something about the user, it wouldn't be good if they got leaked. In addition to revealing something personal about the user, they could also help attackers to make better guesses.

Answers to secret questions should be hashed, as these could be intimate secrets. It can be a good idea to hash a sanitized form, such as lowercased and trimmed, to make it easier for users to reenter correctly.

As for other fields, it's case by case, and depends on many factors. You really need to think through each and every one of them, and evaluate in terms of sensitivity, and decide which method is prudent, or overengineering, or paranoia.

Don't forget to secure the communication channel too. For example if the system is accessible via web, make sure it's https, otherwise your hashing and encrypting makes little difference to your overall security, as everything can be eavesdropped en route between your users and your website.

UPDATE

As @MichaelT pointed out in a comment,
the Payment Card Industry Data Security Standard (PCI DSS) document seems to be a comprehensive document, and well worth reading if you're serious about securing your customer data.
The documents library of PCI may have other interesting items too.

Title: What kind of user info is ok to be stored as plain text in SQL Database?

Body:
I'm practicing around building e-commerce asp.net applications that allows for users to register to the site and their user credentials are stored in a MySQL database. In my sample project the registration asks for the users username, password, full name, phone #, email, home address (for shipping of products purposes).

I know its good practice to store the user's password as a salted hash.  But is there any other info that should be stored the same way or not?  For example should the username also be stored as a salted hash or even encrypted?

I guess I'm just wondering what kinds of information is it ok to be stored in plain text in MySQL database for an asp.net web app? And which items are recommended to be stored in a salted hash? And which items should be stored using encryption?


问:
Workaround for unit testing Core Data in Swift
I am still pretty new to programming, but my first app was recently approved and is now for sale on the App Store. My app uses Core Data and is written in Swift. After some initial difficulties, I decide to write the app without unit tests. Now I'd like to implement unit tests to prevent regression.

My managed objects are created inside class methods in my NSManagedObject subclasses and use a global variable "context" which I declare in AppDelegate to store the NSManagedObjectContext created in Apple's default code. I know that global variables are generally discouraged but this approach makes the most sense to me, is easy to write, and hasn't let to any bugs or other issues inside the app itself. Unfortunately, this makes it difficult to unit test. I've tried several different approaches to creating a Core Data stack inside my test target, but I can't seem to get anything to work without rewriting lots of my app code. I really don't want to do that just to make it testable. I've considered using frameworks such as Quick/Nimble or Magical Record but I don't see how that would help my problem.

I did figure out a workaround, but I'm curious if people think this is a bad idea: I created a class in my primary target (non testing) called TestingClass. In my first ViewController's viewDidAppear, I call the startTests method. TestingClass is written in strait Swift with no testing frameworks. I have several if statements which are supposed to be false. If they are true they add a string to an array. When the tests are complete, if the array count is > 0, it prints out the contents and aborts.

I am planning on using this until my update is ready to ship. When it is, I will disable the TestingClass and remove my call to it. I'm curious if anyone has ever done anything like this. Should I just figure out a way to do tests the "right" way?

答:
Let's look at the broader question first.  In some ways, your question boils down to the balance of pragmatism versus the theoretical "best way" for coding.  I'm in the pragmatic programming camp, especially with your particular situation.  Pragmatic coding means we work around the limitations that the current software stack imposes.

In your particular case, with your particular understanding of the stack, you're running into a challenge.  You've identified a work-around and you've made things work for the time being.  Part of those challenges are possibly introduced by your use of global variables, but as you stated, it made sense for the information that needed to be stored.

I think using a TestingClass is a perfectly valid approach since you're fulfilling the purpose of testing (making sure things operate as expected) and you're also working within the constraints, as you understand them, of the application you created.  You certainly wouldn't be the first to put a test harness in place during development and then remove it prior to releasing the app.

You do run some risks with that approach.  Specifically, if you forget to disable that class before releasing to production, that could create problems for you.  Likewise, you effectively have to duplicate all of your code between the main path and the testing path.  So you run a risk of a bug escaping if the testing path doesn't exactly reflect how the main path operates.  Finally, it does build up complex test cases which can be more difficult to debug because you have to unwind things to understand where it broke.

So, as far as the particular approach that you've taken - it's valid enough.

It may not be "pure" in the sense of following traditional, automated unit testing, but I think that pragmatism needs to rule the day.  People don't buy your application because of the unit tests, they buy your app because it works.  Your approach to unit testing provides regression testing and allows you to keep focused on developing new features.


答:
It can be extremely hard to unit test code that relies on complex system frameworks, even for very experienced programmers. I would try to unit test as much other code as you can first.

(also, never put it code that you have to manually change between debug and release versions! It's inevitable you'll make a mistake somewhere)

Title: Workaround for unit testing Core Data in Swift

Body:
I am still pretty new to programming, but my first app was recently approved and is now for sale on the App Store. My app uses Core Data and is written in Swift. After some initial difficulties, I decide to write the app without unit tests. Now I'd like to implement unit tests to prevent regression.

My managed objects are created inside class methods in my NSManagedObject subclasses and use a global variable "context" which I declare in AppDelegate to store the NSManagedObjectContext created in Apple's default code. I know that global variables are generally discouraged but this approach makes the most sense to me, is easy to write, and hasn't let to any bugs or other issues inside the app itself. Unfortunately, this makes it difficult to unit test. I've tried several different approaches to creating a Core Data stack inside my test target, but I can't seem to get anything to work without rewriting lots of my app code. I really don't want to do that just to make it testable. I've considered using frameworks such as Quick/Nimble or Magical Record but I don't see how that would help my problem.

I did figure out a workaround, but I'm curious if people think this is a bad idea: I created a class in my primary target (non testing) called TestingClass. In my first ViewController's viewDidAppear, I call the startTests method. TestingClass is written in strait Swift with no testing frameworks. I have several if statements which are supposed to be false. If they are true they add a string to an array. When the tests are complete, if the array count is > 0, it prints out the contents and aborts.

I am planning on using this until my update is ready to ship. When it is, I will disable the TestingClass and remove my call to it. I'm curious if anyone has ever done anything like this. Should I just figure out a way to do tests the "right" way?


问:
Design a Queuing Solution with Clustering and Multiple Consumers
It is a Design Problem which I am listing out here.

I have different set of business operations that are carried out for different business entities.

Operations:

Operation A

Operation B

Operation C

For Example I have an Entity A. Entity A's data could be in parts, for example:

Entity A's (Jan Data)

Entity B's (Feb Data) etc.

To complete a Use Case all Operations (A,B,C) should be performed. Now these operations are performed and are independent of each other and can be performed in parallel, the only condition is that they should be of different Entities. So Entity A can't have all the operations (A, B or C) executing in parallel. And these operations are running on server side.

How to scale this and provide a solution?

I am thinking of following solution and would like to have inputs from the community on this.

I am thinking of three Queues for operations which I mentioned above

Queue A carrying out Operation A

Queue B carrying out Operation B

Queue C carrying out Operation C

And all the Consumers will be listening to these Queues.

Consumer A (or multiple consumers)

Consumer B (or multiple consumers)

Consumer C (or multiple consumers)

And my server would be load balanced, and I will be having a Single Message Queue containing these three queues.

So it is possible that I have 2 servers running and on every server there are for example 5 threads (Consumers) running, so there will be 10 instances of Consumer A running in parallel picking the data from the Message Queue A.

As I stated earlier that for the same entity A(that is the business use case which I have) all these operations (Operation A, Operation B and Operation C) can't be running in parallel, they should be only of them being executed.

So what I am thinking is to have a database entry for the Entity A and all the consumers must check whether there is a Database Entry for Entity A,

if not then

Make an entry to Database for Entity A

Go and execute the Operation

Remove the Entry from the Database for Entity A

if there is an entry in Database found

Enqueue the Data for Entity A again from the Queue where it was picked.

Is there any better solution possible for such a design problem?

答:
This sounds like a classic case for the routing slip pattern.

This approach is exactly as you described - separate queues for each consumer / message processor.  Only one consumer can work on a given message (Entity) at a time, but the consumers are free to work on any messages that are in their queue.

The main benefit of this approach is that you don't have to know the message route when you're crafting the code.  You can define run-time routing based upon the message type; load on the individual consumers; or whatever makes sense for your requirements.

The biggest advantages of this approach are:

Each consumer maintains its independence from the other consumers.  A long running consumer process can be individually supplemented by adding additional resources.  Or if your consumers support it, additional resource can be dynamically added or shifted based upon current workloads.

Avoiding the need for database entries and locking.  Generally speaking, DBs don't handle large scale event messaging like this very well.  You can make it work, but the solution tends to be brittle and prone to breaking when requirements change.