问:
Handling multiple packet types in Java 8
I have a Netty-based game server implementation that handles 40 or so distinct packets with their own serialization structure, for brevity I'll refer to them as FooPacket, BarPacket, ... These packet types have been assigned consecutive numerical "packet types", which are unsigned bytes. For example, FooPacket is type 0x01, BarPacket is type 0x02, etc...

All of these packets extend an abstract class, MyGameNetworkPacket.

My current approach with Netty is to use an initial decoding layer to convert a TCP stream into a series of unparsed packet objects, which are defined as consisting of a packet type, length, and buffer containing the actual packet contents. (no byte stuffing is performed). I then feed this packet down the pipeline to one of a few "deserializing processors", each of which handles a set of packet types that are semantically related to each other (for example one such processor might handle connection state messages, while another may handle packets related to a certain aspect of the game itself). As per the design of Netty's MessageToMessageDecoder usage, my decoder is implemented as:

```<code>protected void decode (ChannelHandlerContext ctx, UnparsedPacket msg, List<Object> out)
        throws Exception {
    switch (msg.command) {
        case FooPacket.COMMAND_ID:
            FooPacket fooPacket = new FooPacket(msg.frame);
            out.add(fooPacket);
            break;
        case BarPacket.COMMAND_ID:
            BarPacket barPacket = new BarPacket(msg.frame);
            out.add(barPacket);
            break;
    }

}
</code>```

Once I get a structure decided upon I can easily create this with a code generator.

In addition, I override public boolean acceptInboundMessage(Object) to specify if an unparsed packet should be handled by this decoder.

This is attaining a bit of what appears to be a code-smell for me, so I was looking into alternative solutions, such as:

Having an array whose (integer keys) map to values of a lambda that takes a RawPacket and returns the parsed packet. This seems like a somewhat weird way to use an array and requires that I manually maintain the definition of that array so that its index-element mapping exactly matches the actual packet type to packet structure mapping already in use.

Having a map structure that does the same thing as the array. Similar pitfalls, but somewhat more maintainable.

Are these any more novel ways to approach this that I haven't thought of yet?

答:
What you have described, in one way or another, is exactly how anyone would do it and I don't see any problem with this method. </p>

<p>On a side note: you don't have to use lambda functions in your map/array. A simple interface bound method would be cleaner. </p>

Body:
What you have described, in one way or another, is exactly how anyone would do it and I don't see any problem with this method.

On a side note: you don't have to use lambda functions in your map/array. A simple interface bound method would be cleaner.


问:
What specifically does expressive power refer to?
Expressive Power is defined by Wikipedia as:

.. the breadth of ideas that can be represented and communicated in
  that language.

Does "ideas" refer to the things (operations, structures, algorithms, etc.?) we can communicate to the machine? Or does it refer to the "human" concepts that can be captured and communicated with the language to other humans?

How is expressive power assessed and measured?

For instance, if we took a language like JavaScript and imposed a weird restriction on variable names, such as variable must be an 8-digit number preceded by an underscore, matching /^_[0-9]{8}$/, would we lose expressive power?

Or would that only be absurd and annoying?

To clarify:

Is expressive power measured by the general ideas inherent to the language:

integers and strings

loops

conditionals

Or the number of specific, unique ideas that the language can represent:

the integers 1, 2 ... 2^32

strings containing "what does the fox say?" and "wha pah pah pah pah pah pow"

for each frog in my collection of frogs

if frog is green or something then do something

答:
I don't think that variable naming rules really capture what is meant by "expressiveness". I think that "expressiveness" refers to more fundamental things. Consider C# with Linq versus C# before Linq, for example. After the addition of Linq, it became possible to write SQL-like queries directly in the C#. This is a lot more elegant than the prior alternatives, e.g. putting SQL into string literals and then passing it to the server, or iterating over a collection using "for".

Another good example might be languages with prototype-based inheritance. In those languages, it's possible to simply add new methods to an instance or even a class (by whatever name a "class" may go in a given language...) at runtime. You can't really do that in C++ or C#. They lack this degree of expressiveness compared to prototype-based languages. (C# does have the concept of extension methods, and those could certainly be said to add expressiveness.)

ContentLicense: CC BY-SA 3.0


问:
Proper OO design for State and Command
I'm working (a bit) on a (turn-based strategy) game. There are two classes relevant for the question:

State: This is an immutable class, which exposes all its fields (either via getters or another way, as I felt appropriate). The state is a bit complicated, so I decomposed it into several classes in the package ...state

Command: This is an abstract immutable class with a couple of subclasses like MoveCommand(Field from, Field to), PassCommand(), BidCommand(int amount), etc. in the package ...command. All of fields have public getters.

I need one of the two methods

State Command.applyTo(State) or

State State.apply(Command)

returning the new state (obtained by applying the command to the state).

Using the first method looks better at the first sight, since it dispatches to different implementations of applyTo in the subclasses of Command. Unfortunately, it forces me to fiddle with the many details of State in the class Command. In order to make it work, I need something like MutableState, or State.Builder, or a many-args constructor of State, or whatever.

Using the second method looks ugly, as it'd force me to use instanceof (or some other ugly way to simulate the virtual method dispatch). OTOH, it would concentrate the working with State in the class itself.

So I think the first method is the way to go. With Command and State each in its own package it means that MutableState (or whatever gets used for building the resulting State) need to be a public class since there are no friends in Java. No real problem, but not nice, is it?

So what is the proper design?

答:
I ended up with some mixed design:

The state consists of two parts:

StateData representing

the board

the card stacks of both players

and other long-term things

StateControl representing the intermediate steps like

when a player has selected an own unit as an attacker, but not yet the target

when one of many similar transient situation occurs

The latter uses the state pattern. Everything is immutable and I've dropped the mutable counterpart. With the help of Lombok Wither, it works just fine.

I'm using Command.applyTo(State) which sometimes just delegates to helper methods State.apply(Command), so there are actually both variants.

The immutability lead to some unnecessary allocations like

```<code>State move(Field from, Field to) {
    Group g = getGroupFromField(from);
    return this
        .withField(from, EMPTY_GROUP) // throw-away state
        .withField(to, g);
}
</code>```

but short-living objects are cheap and the object is actually rather small as it consists of a couple of references to other small immutable objects. Sometimes, there are more throw-away intermediates, which made me to use a mutable counterpart as a builder, but this was cluttering the design too much.

The immutability also made the code a bit longer, but surely less error-prone. It also saved me from coding any copying methods and I believe it'll show its advantages when/if I code the game AI.

Title: Proper OO design for State and Command

Body:
I ended up with some mixed design:

The state consists of two parts:

StateData representing

the board

the card stacks of both players

and other long-term things

StateControl representing the intermediate steps like

when a player has selected an own unit as an attacker, but not yet the target

when one of many similar transient situation occurs

The latter uses the state pattern. Everything is immutable and I've dropped the mutable counterpart. With the help of Lombok Wither, it works just fine.

I'm using Command.applyTo(State) which sometimes just delegates to helper methods State.apply(Command), so there are actually both variants.

The immutability lead to some unnecessary allocations like

State move(Field from, Field to) {
    Group g = getGroupFromField(from);
    return this
        .withField(from, EMPTY_GROUP) // throw-away state
        .withField(to, g);
}

but short-living objects are cheap and the object is actually rather small as it consists of a couple of references to other small immutable objects. Sometimes, there are more throw-away intermediates, which made me to use a mutable counterpart as a builder, but this was cluttering the design too much.

The immutability also made the code a bit longer, but surely less error-prone. It also saved me from coding any copying methods and I believe it'll show its advantages when/if I code the game AI.


答:
TLDR: If a feature is missing but can be expressed in other ways it is not a lack of expressiveness. If you can envision an algorithm in your mind or even implement it in one language but another language is somehow structured in a way that makes it impossible to implement the algorithm it is an expressiveness problem*.

Variable naming restrictions do not reduce expressiveness (unless there are so few names that one cannot express all algorithms anymore and one cannot fake variables with something like arrays + indexes).

A simple example of a lack of expressive power is this: You have to do_homework and bring_down_trash. This is easily written in code:

```<code>do_homework();
bring_down_trash();
</code>```

This solution looks pretty straightforward but actually do_homework and bring_down_trash are unordered, one could also write:

```<code>bring_down_trash();
do_homework();
</code>```

Which is equally imprecise because it does not express that we did not intend to enforce an order. We also do not want to use threads. We want to say something like this:

```<code>compiler_or_interpreter_pick_one(
    {
        do_homework();
        bring_down_trash();
    },
    {
        bring_down_trash();
        do_homework();
    }
);
</code>```

As far as I know this is very tricky to impossible to express in any programming language.

An example that bugs me to no end is that it is impossible in Java to have an array of objects. You can make an array of pointers to objects but that does not have the same memory layout (speak efficiency).

Taking an example from another answer: C++ does not support adding methods to a class or an instance. This is true, however, it does not limit the expressiveness of C++.

struct Extensible{
    std::vector<std::function<void(Extensible *)>> instanceExtensions;
    static std::vector<std::function<void(Extensible *)>> classExtensions;
};
```

This is a class to which you can add, remove and call an arbitrary number of member functions for instances and the class. Technically C++ is probably more expressive in this regard than programming languages that actually support this feature because in C++ you can choose how to store the functions (vector vs array vs forward_list).

*Some languages have a lack of expressiveness as a feature. Typically they make it impossible to write infinite loops. This can make the halting problem solvable and allow automatic proves for correctness.

Title: What specifically does expressive power refer to?

Body:
Expressive Power is defined by Wikipedia as:

.. the breadth of ideas that can be represented and communicated in
  that language.

Does "ideas" refer to the things (operations, structures, algorithms, etc.?) we can communicate to the machine? Or does it refer to the "human" concepts that can be captured and communicated with the language to other humans?

How is expressive power assessed and measured?

For instance, if we took a language like JavaScript and imposed a weird restriction on variable names, such as variable must be an 8-digit number preceded by an underscore, matching /^_[0-9]{8}$/, would we lose expressive power?

Or would that only be absurd and annoying?

To clarify:

Is expressive power measured by the general ideas inherent to the language:

integers and strings

loops

conditionals

Or the number of specific, unique ideas that the language can represent:

the integers 1, 2 ... 2^32

strings containing "what does the fox say?" and "wha pah pah pah pah pah pow"

for each frog in my collection of frogs

if frog is green or something then do something

Body:
TLDR: If a feature is missing but can be expressed in other ways it is not a lack of expressiveness. If you can envision an algorithm in your mind or even implement it in one language but another language is somehow structured in a way that makes it impossible to implement the algorithm it is an expressiveness problem*.

Variable naming restrictions do not reduce expressiveness (unless there are so few names that one cannot express all algorithms anymore and one cannot fake variables with something like arrays + indexes).

A simple example of a lack of expressive power is this: You have to do_homework and bring_down_trash. This is easily written in code:

do_homework();
bring_down_trash();

This solution looks pretty straightforward but actually do_homework and bring_down_trash are unordered, one could also write:

bring_down_trash();
do_homework();

Which is equally imprecise because it does not express that we did not intend to enforce an order. We also do not want to use threads. We want to say something like this:

compiler_or_interpreter_pick_one(
    {
        do_homework();
        bring_down_trash();
    },
    {
        bring_down_trash();
        do_homework();
    }
);

As far as I know this is very tricky to impossible to express in any programming language.

An example that bugs me to no end is that it is impossible in Java to have an array of objects. You can make an array of pointers to objects but that does not have the same memory layout (speak efficiency).

Taking an example from another answer: C++ does not support adding methods to a class or an instance. This is true, however, it does not limit the expressiveness of C++.

struct Extensible{
    std::vector<std::function<void(Extensible *)>> instanceExtensions;
    static std::vector<std::function<void(Extensible *)>> classExtensions;
};

This is a class to which you can add, remove and call an arbitrary number of member functions for instances and the class. Technically C++ is probably more expressive in this regard than programming languages that actually support this feature because in C++ you can choose how to store the functions (vector vs array vs forward_list).

*Some languages have a lack of expressiveness as a feature. Typically they make it impossible to write infinite loops. This can make the halting problem solvable and allow automatic proves for correctness.


答:
The landmark paper on expressiveness is On the Expressive Power of Programming Languages by Matthias Felleisen (1991). It contains a mathematically rigorous definition of language expressiveness.

Intuitively, if every program that can be written in language A can also be written in language B with only local transformations, but there are some programs written in language B which cannot be written in language A without changing their global structure (i.e. not with just purely local transformations), then language B is more expressive than language A.

One nice property of this definition is that it admits the possibility that there are pairs of languages where there are programs in X which cannot be expressed in Y and programs in Y which cannot be expressed in X, and thus the languages are distinct, but neither language is more expressive than the other. This meshes well with our real-world experience of there being some languages which are good at some things and some which are good at other things, and neither is generally "better" than the other.


答:
As referenced by the Wikipedia article, expressive power refers to the set of programs that can be expressed in the language. Everything you think of as a "programming language" (JavaScript, LISP, C#, Perl, etc.) are essentially Turing complete, meaning that they can express anything said to be "computable".

However, it should be pretty clear that regular expressions are not as expressive as regular programming language. Furthermore, shell wildcards are somewhat less expressive than regular expressions.

A version of SQL with common table expressions is more expressive than a version without because CTEs allow you to represent recursive queries that would otherwise be impossible to express in SQL.


问:
Should all HTTP requests including credentials be made using a POST even if it is actually just a request for data?
Assume there is a request which is going to look up a list of items from a service which requires authorisation (e.g. it's behind a Basic Authentication domain). If the service didn't require authentication, I would always make this request as a GET (it's idempotent). But because the credentials would end up in the query string, I'm basically required to do this as a POST. Is there any alternative to this method?</p>

答: It really depends. You could for example have a POST request to query the current time (or the current used memory in the server process, or the number of processed HTTP requests). It has to be a POST because it is not idempotent, but you might decide to accept such a simple status-querying request even without credentials or authentications.


问:
How to capture "Display advertisement" use case?
What kind of use case it would be for to "show ad in part of the view"? Who could be the actor to relate with? User or System? As user has no specific goal to see ads, i am wondering what is the best way to capture this in use case diagram?

Any assistance will be helpful

答:
I think "Display advertisement” is not a use case of its own but a Cross-cutting_concern
that can be attached to many different use-cases:

from Use_case@wikipedia

```<code>    a use case is a list of steps,
    typically defining interactions between a role [...] and a system, to achieve a goal.
</code>```

the end-user does not visit a car-webportal to see advertisments but to achive a goal: i.e. find infos about a certain type of car.

Showing advertisments is a Cross-cutting feature.

The goal of the car-webportal is

to attract car-entusiasts

and to make money by selling car-related ads.

the more car-entusiasts visiting the website the more money they make.

Body:
I think "Display advertisement” is not a use case of its own but a Cross-cutting_concern
that can be attached to many different use-cases:

from Use_case@wikipedia

    a use case is a list of steps,
    typically defining interactions between a role [...] and a system, to achieve a goal.

the end-user does not visit a car-webportal to see advertisments but to achive a goal: i.e. find infos about a certain type of car.

Showing advertisments is a Cross-cutting feature.

The goal of the car-webportal is

to attract car-entusiasts

and to make money by selling car-related ads.

the more car-entusiasts visiting the website the more money they make.


问:
How do you set and check a single bit in a programming language that does not support bitwise operations?
I'm using a programming language (more a scripting language) that does not support any bitwise operators like AND, OR, XOR, NOT (and shift as well).

Common arithmetic and logical operations like + - * / % > >= < <= == !=, logical AND, OR, NOT and control flow (while, for, if,...) are supported however. It is like a "subset of C", but without these binary operators. My question does not target that particular language anyway.

I was wondering if there is any (mathematical ?) way to set and check a bit at a specific position in a programming language that does not support bitwise operations :

```<code>a = 0;               //00000000b
a = togglebit(a, 5); //00100000b
a = togglebit(a, 2); //00100100b

a = 0xFE;            //11111110b
bool result = checkbit(a, 4); //true
</code>```

For example, there is a way to perform a left or right binary shift using integer multiplication or division :

```<code>a = a * 2; //similar to left  shift : a = a << 1;
a = a / 2; //similar to right shift : a = a >> 1;
</code>```

I'm looking for something similar but for setting or checking a flag.

答:
To check the n th bit, shift right n times. If the bit is set, the result will be odd (numbers are odd if and only if their final bit is 1.)

```<code>function checkbit(a, n)
  n times:
    a = a / 2   (integer division)
  return a % 2
end
</code>```

To set the n th bit, add 2^n only if the bit is not yet set.

```<code>function pow2(n):   (returns 2^n)
  result = 1
  n times: result = result * 2
  return result
end

function setbit(a, n)
  if checkbit(a, n):
    return a
  else:
    return a + pow2(n)
end
</code>```

Toggling it is similar, but we subtract if the bit is already set:

```<code>function togglebit(a, n)
  if checkbit(a, n):
    return a - pow2(n)
  else:
    return a + pow2(n)
end
</code>```

Bitwise negation depends on how big your bitmasks are; specifically, the bitwise negative of an n-bit bitmask a is 2^n-1-a. If you're using 16 bits, it would be 65535-a.

Body:
To check the n th bit, shift right n times. If the bit is set, the result will be odd (numbers are odd if and only if their final bit is 1.)

function checkbit(a, n)
  n times:
    a = a / 2   (integer division)
  return a % 2
end

To set the n th bit, add 2^n only if the bit is not yet set.

function pow2(n):   (returns 2^n)
  result = 1
  n times: result = result * 2
  return result
end

function setbit(a, n)
  if checkbit(a, n):
    return a
  else:
    return a + pow2(n)
end

Toggling it is similar, but we subtract if the bit is already set:

function togglebit(a, n)
  if checkbit(a, n):
    return a - pow2(n)
  else:
    return a + pow2(n)
end

Bitwise negation depends on how big your bitmasks are; specifically, the bitwise negative of an n-bit bitmask a is 2^n-1-a. If you're using 16 bits, it would be 65535-a.


问:
Long Keywords like `function` and `namespace`
In many English-based programming languages like C++ and JavaScript, there exist long keywords like function, namespace, exception (in OCaml languages) and such. Do you think shorter keywords like func should replace them? Why or why not? What about replacing them with digraph operators?

The long keywords we will be mainly talking about, but not limited to, are mainly from curly-brace imperative languages: function, namespace, implements, instanceof and synchronized (I always misspell that).
You should also show the examples from your favourite programming language.

答: Time to change your editor. Most editors highlights the keywords and hence it is really easy to find the spell errors. Because of this people normally didn't notice this or don't care about this. </p>

ContentLicense: CC BY-SA 2.5


问:
class hierarchy with structurally different subclasses
I want to implement a protocol layer which sits on top of the TCP/IP stack. There is a limited set of PDUs that can be sent and for each PDU there is a class which represents it in a structured form. Each class has a function to serialize the structured data into a ready-to-transmit form, and deserialize them into a structured form.

These PDUs are structurally very different, for example:

```<code>struct a_associate_ac : property
{
      a_associate_ac() = default;
      void from_pdu(std::vector<unsigned char> pdu) override;
      std::vector<unsigned char> make_pdu() const override;
      pdu::TYPE type() const override;

      std::string called_ae;
      std::string calling_ae;
      std::string application_context;

      struct presentation_context
      {
            enum class RESULT
            {
               ACCEPTANCE = 0x00, USER_REJEC = 0x01,
               PROV_REJEC_NO_REASON = 0x02,
               ABSTR_CONT_NOT_SUPP = 0x03,
               TRANFS_SYNT_NOT_SUPP = 0x04
            };

            presentation_context() = default;
            unsigned char id;
            RESULT result_;
            std::string transfer_syntax;
      };

      std::vector<presentation_context> pres_contexts;
      std::size_t max_message_length;
};
</code>```

compared to:

```<code>struct a_associate_rj: property
{
      a_associate_rj() = default;
      void from_pdu(std::vector<unsigned char> pdu) override;
      std::vector<unsigned char> make_pdu() const override ;
      pdu::TYPE type() const override;

      enum class SOURCE : unsigned char
      {
         UL_SERVICE_USER = 0x01, UL_SERVICE_PROV_ACSE = 0x02,
         UL_SERVICE_PROV_PRESREL = 0x03
      };
      enum class REASON : unsigned char
      {
         NOT_SPECIFIED = 0x01, APPL_CONT_NOT_SUPP = 0x02, CALLING_AE_NOT_RECOG = 0x03,
         CALLED_AE_NOT_RECOG = 0x07
      };

      REASON reason_;
      SOURCE source_;
};
</code>```

All these classes inherit from an abstract superclass property. property is used by the layer class, which implements the protocol, in two member functions:

```<code>void send(const property* p);
std::unique_ptr<const property> receive();
</code>```

This means if the user of the layer class receives a property and wants to access its members, they must check what kind of property was received using property::type() and downcast it to that type, which I find is quite irritating.

What can be done to solve this problem?

答:
It depends a little bit of what you are doing with these properties, but one pattern that would get around the explicit casting would be double-dispatch or 'visitor'. It's a common pattern that is used in operating on trees but it think it might suit your need. In c++ the only disadvantage is that there is a point where you might need to refer to all your properties explicitly. This is what a stub for this might look like:

```<code>class Property {
    virtual void visit(Visitor *visitor) = 0;
}

class SpecificPropertyA {
     void visit(Visitor *visitor) {
        visitor->handle(this);
    }
}

class Visitor {

    void handle(Property *)  {
        // This is catch all and will deal with not implemented handle functions
    }

    void handle(SpecificPropertyA* property) {
        // Do the specific work here
    }

    void handle(SpecificPropertyB* property) {
        // Do the specfic work here
    }
}
</code>```

You can have as many different types of Visitors that you want, by deriving from the visitor interface. E.g. implementing a logger as opposed to a processor.

Please note that this is just one way of separating functionality from data, depending on the problem you are trying to solve it might just be easier to supply each of your property with a process() function that gets called and does the appropriate work without having to expose the type.

Body:
It depends a little bit of what you are doing with these properties, but one pattern that would get around the explicit casting would be double-dispatch or 'visitor'. It's a common pattern that is used in operating on trees but it think it might suit your need. In c++ the only disadvantage is that there is a point where you might need to refer to all your properties explicitly. This is what a stub for this might look like:

class Property {
    virtual void visit(Visitor *visitor) = 0;
}

class SpecificPropertyA {
     void visit(Visitor *visitor) {
        visitor->handle(this);
    }
}

class Visitor {

    void handle(Property *)  {
        // This is catch all and will deal with not implemented handle functions
    }

    void handle(SpecificPropertyA* property) {
        // Do the specific work here
    }

    void handle(SpecificPropertyB* property) {
        // Do the specfic work here
    }
}

You can have as many different types of Visitors that you want, by deriving from the visitor interface. E.g. implementing a logger as opposed to a processor.

Please note that this is just one way of separating functionality from data, depending on the problem you are trying to solve it might just be easier to supply each of your property with a process() function that gets called and does the appropriate work without having to expose the type.


答:
Ideally, you would override the decode method for each packet type.

But the decode method isn't part of the specific subclass.  That is why the switch, or a map that returns the packet-specific factory is justified.  It smells because you have to repeat the same code over and over and the method has dependencies on all 40 subclasses.  But if the code is generated, I don't see a problem there.

If you want more independence and avoid repeating the same code for each and every subclass, you could map your integer to the packet-specific Class, create an instance from the class and ask the instance to initialize itself from the frame.

You would have something like:

```<code>static Class<? extends MyGameNetworkPacket>[] packetClasses;
static {
    packetClasses = new Class[50];
    packetClasses[1] = FooPacket.class;
    packetClasses[2] = BarPacket.class;
    packetClasses[5] = GimmeFivePacket.class;
}
</code>```

And in the decode method:

```<code>Class<? extends MyGameNetworkPacket> packetClass = packetClasses[msg.command];
if( packetClass != null ){
    MyGameNetworkPacket pkt;
    try {
        pkt = packetClass.newInstance();
    } catch( InstantiationException | IllegalAccessException e ){
        throw new RuntimeException("Failed to create instance.", e);
    }
    pkt.fillFrom(msg.frame);
    out.add(pkt);
} else {
    throw new RuntimeException("Invalid command ID: " + msg.command + ".");
}
</code>```

It doesn't look very elegant because of the try/catch for errors even though they cannot happen if the classes were written properly.  But it reduces the dependency on the subclasses to the reference to their class.  You could even initialize the array from an external configuration file that contains the class name for each command ID.

Title: Handling multiple packet types in Java 8

Body:
I have a Netty-based game server implementation that handles 40 or so distinct packets with their own serialization structure, for brevity I'll refer to them as FooPacket, BarPacket, ... These packet types have been assigned consecutive numerical "packet types", which are unsigned bytes. For example, FooPacket is type 0x01, BarPacket is type 0x02, etc...

All of these packets extend an abstract class, MyGameNetworkPacket.

My current approach with Netty is to use an initial decoding layer to convert a TCP stream into a series of unparsed packet objects, which are defined as consisting of a packet type, length, and buffer containing the actual packet contents. (no byte stuffing is performed). I then feed this packet down the pipeline to one of a few "deserializing processors", each of which handles a set of packet types that are semantically related to each other (for example one such processor might handle connection state messages, while another may handle packets related to a certain aspect of the game itself). As per the design of Netty's MessageToMessageDecoder usage, my decoder is implemented as:

```<code>protected void decode (ChannelHandlerContext ctx, UnparsedPacket msg, List<Object> out)
        throws Exception {
    switch (msg.command) {
        case FooPacket.COMMAND_ID:
            FooPacket fooPacket = new FooPacket(msg.frame);
            out.add(fooPacket);
            break;
        case BarPacket.COMMAND_ID:
            BarPacket barPacket = new BarPacket(msg.frame);
            out.add(barPacket);
            break;
    }

}
</code>```

Once I get a structure decided upon I can easily create this with a code generator.

In addition, I override public boolean acceptInboundMessage(Object) to specify if an unparsed packet should be handled by this decoder.

This is attaining a bit of what appears to be a code-smell for me, so I was looking into alternative solutions, such as:

Having an array whose (integer keys) map to values of a lambda that takes a RawPacket and returns the parsed packet. This seems like a somewhat weird way to use an array and requires that I manually maintain the definition of that array so that its index-element mapping exactly matches the actual packet type to packet structure mapping already in use.

Having a map structure that does the same thing as the array. Similar pitfalls, but somewhat more maintainable.

Are these any more novel ways to approach this that I haven't thought of yet?

Body:
Ideally, you would override the decode method for each packet type.

But the decode method isn't part of the specific subclass.  That is why the switch, or a map that returns the packet-specific factory is justified.  It smells because you have to repeat the same code over and over and the method has dependencies on all 40 subclasses.  But if the code is generated, I don't see a problem there.

If you want more independence and avoid repeating the same code for each and every subclass, you could map your integer to the packet-specific Class, create an instance from the class and ask the instance to initialize itself from the frame.

You would have something like:

static Class<? extends MyGameNetworkPacket>[] packetClasses;
static {
    packetClasses = new Class[50];
    packetClasses[1] = FooPacket.class;
    packetClasses[2] = BarPacket.class;
    packetClasses[5] = GimmeFivePacket.class;
}

And in the decode method:

Class<? extends MyGameNetworkPacket> packetClass = packetClasses[msg.command];
if( packetClass != null ){
    MyGameNetworkPacket pkt;
    try {
        pkt = packetClass.newInstance();
    } catch( InstantiationException | IllegalAccessException e ){
        throw new RuntimeException("Failed to create instance.", e);
    }
    pkt.fillFrom(msg.frame);
    out.add(pkt);
} else {
    throw new RuntimeException("Invalid command ID: " + msg.command + ".");
}

It doesn't look very elegant because of the try/catch for errors even though they cannot happen if the classes were written properly.  But it reduces the dependency on the subclasses to the reference to their class.  You could even initialize the array from an external configuration file that contains the class name for each command ID.


问:
Is it ok to restart a BackgroundWorker inside its Completed event
I want a background worker to continue running and occasionally update the user interface. My first idea was to use a BackgroundWorker and in its completed event just fire it up again.

Is using a BackgroundWorker in this fashion acceptable?  Or are there potential issues from using the completed event to trigger the worker?

Below is some Pseudo code of what my intentions are

```<code>class Program
{
    private static BackgroundWorker worker;
    private static Int32 runs = 0;

    static void Main(string[] args)
    {
        worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        worker.RunWorkerAsync(runs);
        Console.ReadLine();
    }

    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        //Do time consuming work
        Thread.Sleep(3000);
    }

    static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //Update the UI and start time consuming work again
        runs++;
        Console.WriteLine("Completed run #" + runs);
        worker.RunWorkerAsync();
    }
}
</code>```

答: if you just want to restart it immediately, it would seem to be a better option to just wrap the DoWork function body in an endless loop.</p>


答:
Using the Backgroundworker in this fashion is not acceptable.  That's why it specifically has a ProgressChanged event.  I would suggest rewriting your app to accept a MaxRuns integer and pass that once to the BGW.  Then inside the BGW worker loop over each run.  At the bottom of each run, you then report progress.

I know your example is a shortened and is a console app.  But in case you ever have a forms app, you could set up a progress bar from 0 - MaxRuns, and have the BGW worker report it's progress back to the UI so the UI can move the progress bar.

On last tip: progress reporting has a parameter named ProgressPercentage.  It is just an int, which can be negative or > 100.  So don't feel constrained between 0 and 100.

EDIT: Example Code

```<code>class Program
</code>```

{
    private static BackgroundWorker worker;
    private static Int32 maxRuns = 3333;

```<code>static void Main(string[] args)
{
    worker = new BackgroundWorker();
    worker.DoWork += worker_DoWork;
    worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    worker.ProgressChanged += worker_ProgressChanged;
    worker.RunWorkerAsync(maxRuns);
    Console.ReadLine();
}

static void worker_DoWork(object sender, DoWorkEventArgs e)
{
    int totalRuns = (int)e.Argument;
    for (int i = 0; i < totalRuns; i++)
    {
        var sw = Stopwatch.StartNew();
        //Do time consuming work
        Thread.Sleep(3000);
        worker.ReportProgress(i, sw.Elapsed);
    }
}

// This method runs in the foreground thread while the background worker is busy.
static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // e.ProgressPercentage is not a true percentage.  Rather it is the Run number.
    var percent = (100 * e.ProgressPercentage) / maxRuns;
    var elapsed = (TimeSpan)e.UserState;
    Console.WriteLine(string.Format("{0}% complete.  Run {1} of {2} took {3}.", percent, e.ProgressPercentage, maxRuns, elapsed));
}

static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Console.WriteLine("Background Completed.");
}
</code>```

}

Title: Is it ok to restart a BackgroundWorker inside its Completed event

Body:
I want a background worker to continue running and occasionally update the user interface. My first idea was to use a BackgroundWorker and in its completed event just fire it up again.

Is using a BackgroundWorker in this fashion acceptable?  Or are there potential issues from using the completed event to trigger the worker?

Below is some Pseudo code of what my intentions are

```<code>class Program
{
    private static BackgroundWorker worker;
    private static Int32 runs = 0;

    static void Main(string[] args)
    {
        worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        worker.RunWorkerAsync(runs);
        Console.ReadLine();
    }

    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        //Do time consuming work
        Thread.Sleep(3000);
    }

    static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //Update the UI and start time consuming work again
        runs++;
        Console.WriteLine("Completed run #" + runs);
        worker.RunWorkerAsync();
    }
}
</code>```

Body:
Using the Backgroundworker in this fashion is not acceptable.  That's why it specifically has a ProgressChanged event.  I would suggest rewriting your app to accept a MaxRuns integer and pass that once to the BGW.  Then inside the BGW worker loop over each run.  At the bottom of each run, you then report progress.

I know your example is a shortened and is a console app.  But in case you ever have a forms app, you could set up a progress bar from 0 - MaxRuns, and have the BGW worker report it's progress back to the UI so the UI can move the progress bar.

On last tip: progress reporting has a parameter named ProgressPercentage.  It is just an int, which can be negative or > 100.  So don't feel constrained between 0 and 100.

EDIT: Example Code

class Program

{
    private static BackgroundWorker worker;
    private static Int32 maxRuns = 3333;

static void Main(string[] args)
{
    worker = new BackgroundWorker();
    worker.DoWork += worker_DoWork;
    worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    worker.ProgressChanged += worker_ProgressChanged;
    worker.RunWorkerAsync(maxRuns);
    Console.ReadLine();
}

static void worker_DoWork(object sender, DoWorkEventArgs e)
{
    int totalRuns = (int)e.Argument;
    for (int i = 0; i < totalRuns; i++)
    {
        var sw = Stopwatch.StartNew();
        //Do time consuming work
        Thread.Sleep(3000);
        worker.ReportProgress(i, sw.Elapsed);
    }
}

// This method runs in the foreground thread while the background worker is busy.
static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // e.ProgressPercentage is not a true percentage.  Rather it is the Run number.
    var percent = (100 * e.ProgressPercentage) / maxRuns;
    var elapsed = (TimeSpan)e.UserState;
    Console.WriteLine(string.Format("{0}% complete.  Run {1} of {2} took {3}.", percent, e.ProgressPercentage, maxRuns, elapsed));
}

static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Console.WriteLine("Background Completed.");
}

}


问:
sanity checks: when do they become paranoid checks
I normally add lots of sanity check clauses in my code. In other words, lots of assertions where the code is instructed to "panic" (usually print as much information as possible when a certain condition doesn't hold and then exit). The point is, many of these sanity checks are obviously redundant one way or the other. On the other hand I've often been bitten by situations were I didn't add a sanity check judging it to be fairly obvious that it can't fail and was proven wrong. So the question is: are there any guidelines / best-practices to decide how much sanity checking is reasonable? Too much sanity checking obviously clutters the code and is a pain to maintain when assumptions change.</p>

答:
It is difficult to argue that:

All input is evil is a solid unquestionable principle, because
if we fail to conform to it, the resulting program will fail to
conform to its requirements. Well we can conform to direct requirements, but, for example, consider requirement that says: "user X could be authorized by valid credential A". It is usually also meant that user Y shouldn't be able to authorize himself with halfvalid credential Y, but nonetheless such things happen.

Garbage in, Garbage out is not a way to process anything you
get, because if something is wrong, then it is better to fail
fast than to produce some undeterministic result and possibly
corrupt the overall application.

So, if we can't proof that some assert(check) is unnecessary, then the check isn't a paranoid one, but, rather, a completely normal protection mechanism for the program against unexpected. And taking into account that formal verification is not something you will use on everyday projects, asserts in code are a necessary burden.

But we have to be realists. It is nearly impossible to check everything whether in some mathematical model or in the working code. And not because there are different kinds of exceptional situations exist (code defects, environment problems...), but because of the sheer complexity.

At best checking everything will lead to linear increase in LOC and some code bloat with duplication (and more code means more defects), at worst we will have combinatorial explosion and inconsistent, often wrong checks in multiple parts of the codebase.

But the most daunting and frustrating of all is the amount of details(exceptional to-check cases) that you have to juggle with.

So, how to adhere to principles that allow to write programs that behave more or less correctly and capable of dealing with unexpected situations, but at the same time do not demand enormous efforts to implement?

Acknowledge our limits and apply efforts accordingly from the conception till the implementation. Systems are complex and hard to understand, so we have to compartmentalize and isolate them as much as possible.

It is important for any software, but with such rigid goals it is even more important - if we decide to get some correctness guarantees for tightly coupled 50-members classes, we are already moving in a wrong direction (possibly dooming us to Sisyphean task, where our asserts and checks will be just like a sieve for incorrect parameters, callbacks and dependencies).

So, design classes and other units of work and interoperation judiciously - spaghetti code and godobjects that provide trustworthy behaviour guarantees are a rare sight.

Use lines of defense and unclean input mechanics. Most units of work(classes, functions...) are also units of encapsulation as per se(class invariants), and they also act as intermediaries between different parts of the system. Function entry point checks, class constructors and accessors checks are the checkpoints in all possible senses - they are the main line of defence for class and the first one for his dependencies. So, if we can guarantee that class VariableGate will have only correct datamembers and allow to pass only correct variables to VariableUser class, then we have already cut a lot of checks from TODO list.

Design by contract augmented by heavy static analysis can be enormously useful. And I don't mean some comments claiming that Foo won't return NULL. I mean full-blown contracts, that are validated by compiler and runtime. They are either do not fail, or fail in a way, that you theoretically can't do anything wrong afterwards. They are the same function entry point checks, class constructors and accessors checks, just in another more formalized and useful form.

NullReferenceException, access violation or segmentation violation while dereferencing null pointers(references) is our friend. It is the most basic design-by-contract element for most of runtimes. Null is nil, as nothing, as something we cannot operate on. But it doesn't mean that we could just write this.importantNotNullVar = varProvider.GetProbablyNotNullVar() and be happy with it - it won't qualify as fail-fast. It means, for example, that chained calls provider.GetExecutor().Do() will fail if GetExecutor() is null whether you check it or use directly. But overall it is still better to adhere to the Law of Demeter and use specialized nested method calls.

P.S.: There is also one topic of an utmost importance - correct state management. We can handle our exceptional cases with exceptions or return codes, or with complete app failure, but regardless of it our actions can corrupt the state of the data being processed. Ideally any operation should be transactional, so that any change to used data is either correct on success, or reverted on failure, but how to organize systems in such a way is an another question.

ContentLicense: CC BY-SA 4.0


答:
Expressive Power is defined by Wikipedia as:

Let's give that page a re-read. One of the first things to note is that it says "language", not "programming language", and most of its examples are not programming languages, e.g. the first example given is a comparison of OWL2 EL and OWL2 RL, which are both ontology languages.

One can apply the concept to programming languages, but also pattern-matching langauges, markup languages, query languages, visual stylesheet langauges, regular expressions (and all the regular languages they refer to) and so on. One can even refer to the expressive power of natural languages like English, which is often done very informally, but with more seriousness when considering the problems related to natural language processing.

Does "ideas" refer to the things (operations, structures, algorithms, etc.?) we can communicate to the machine? Or does it refer to the "human" concepts that can be captured and communicated with the language to other humans?

It refers to what can be expressed in that language, considered purely as a thing in itself.

For example, (I'll use javascript throughout for my examples, because your question indicates that its one of the languages you know) consider the javascript statement:

```<code>var x = 3 + 4;
</code>```

This represents that the value sum of 3 and 4 is computed and the value associated with a label x within a given namespace scope.

If we destroyed all the computers in the world and wrote that code on a piece of paper, it would remain that in javascript it still had that same meaning; we wouldn't be able to run such code on anything, but the abstract definition of the language is still something we could talk about.

This may seem pedantic, but it's actually quite important that languages are things that can be reasoned about in the abstract without consideration of real computers. For one thing, people reasoning about theoretical points of computer languages that were not yet feasible in practice is one of the things that has got us to where we are today; computers need computer science, but computer science does not need computers, just the idea of a computation.

Of course, we do use computers in the real world, and these days there are a lot of people using them in practice rather than a few specialists discussing them in theory. The page you linked to says:

The term expressive power may be used with a range of meaning. It may mean a measure of the ideas expressible in that language:

regardless of ease (theoretical expressivity)

concisely and readily (practical expressivity)

The first sense dominates in areas of mathematics and logic that deal with the formal description of languages and their meaning, such as formal language theory, mathematical logic and process algebra.

In informal discussions, the term often refers to the second sense, or to both. This is often the case when discussing programming languages. Efforts have been made to formalize these informal uses of the term

Of these two uses of the term, the first's practical impact relates solely to the what can be conveyed to the computer.

The second relates more to human understanding in both reading and writing, though the degree to which it does so, differs a lot between uses, since they are informal and as such are not rigourously defined.

For instance, if we took a language like JavaScript and imposed a weird restriction on variable names, such as variable must be an 8-digit number preceded by an underscore, matching /^_[0-9]{8}$/, would we lose expressive power?

By the formal definition, we've lost no expressive power: We're restricted to 100,000,000 variables, but if we really needed to we could get around this by creating objects to hold more variables within the newly-created namespace. As such any program written in javascript today could be rewritten in this new form, so they are equally expressive.

By the informal definition, we've lost some, but just how much depends on just how informal we're being, which will vary because again you can't say what is "the rule" about an informl use. We might say we've lost a tiny amount, because programs with more than 100,000,000 variables in the same namespace have to be rewritten beyond a simple substitution. An even more informal use again would refer to the mental impact of such ungainly variable names on human comprehensive.

Its also worth noting that people will informally consider things that are not strictly part of the language at all. Consider the changes in Javascript from its creation until today.

By the most formal definition, there has been pretty unchanged in expressiveness; it was Turing complete to start with, after all.

By a more informal definition, it has become considerably more expressive in certain things like array manipulation, exception handling and (perhaps most of all) in the inclusion of regular expressions. These don't do anything that couldn't be done in javascript before, though they can often do something in a few lines and a subsecond execution time that would take kilobytes of code to write in javascript1.0 and a long time to run.

By a much more informal definition again, the change from javascript's first use in browsers (able to change the values of form inputs, document.write while the page is first being parsed and move to a new location or go back or forward in the history, but pretty much nothing else) to that today (able to change just about anything on the page, including on the basis of data from server calls) is absolutely immense, though most of it doesn't relate to javascript but to the object models and APIs made available, rather than the language (e.g. vbscript in IE benefitted from those changes equally).

To my mind, that last use is so informal as to not really be correct, but that's the problem with informal definitions.

By the formal defintion, it really hasn't become more expressive at all.

Body:
Expressive Power is defined by Wikipedia as:

Let's give that page a re-read. One of the first things to note is that it says "language", not "programming language", and most of its examples are not programming languages, e.g. the first example given is a comparison of OWL2 EL and OWL2 RL, which are both ontology languages.

One can apply the concept to programming languages, but also pattern-matching langauges, markup languages, query languages, visual stylesheet langauges, regular expressions (and all the regular languages they refer to) and so on. One can even refer to the expressive power of natural languages like English, which is often done very informally, but with more seriousness when considering the problems related to natural language processing.

Does "ideas" refer to the things (operations, structures, algorithms, etc.?) we can communicate to the machine? Or does it refer to the "human" concepts that can be captured and communicated with the language to other humans?

It refers to what can be expressed in that language, considered purely as a thing in itself.

For example, (I'll use javascript throughout for my examples, because your question indicates that its one of the languages you know) consider the javascript statement:

var x = 3 + 4;

This represents that the value sum of 3 and 4 is computed and the value associated with a label x within a given namespace scope.

If we destroyed all the computers in the world and wrote that code on a piece of paper, it would remain that in javascript it still had that same meaning; we wouldn't be able to run such code on anything, but the abstract definition of the language is still something we could talk about.

This may seem pedantic, but it's actually quite important that languages are things that can be reasoned about in the abstract without consideration of real computers. For one thing, people reasoning about theoretical points of computer languages that were not yet feasible in practice is one of the things that has got us to where we are today; computers need computer science, but computer science does not need computers, just the idea of a computation.

Of course, we do use computers in the real world, and these days there are a lot of people using them in practice rather than a few specialists discussing them in theory. The page you linked to says:

The term expressive power may be used with a range of meaning. It may mean a measure of the ideas expressible in that language:

regardless of ease (theoretical expressivity)

concisely and readily (practical expressivity)

The first sense dominates in areas of mathematics and logic that deal with the formal description of languages and their meaning, such as formal language theory, mathematical logic and process algebra.

In informal discussions, the term often refers to the second sense, or to both. This is often the case when discussing programming languages. Efforts have been made to formalize these informal uses of the term

Of these two uses of the term, the first's practical impact relates solely to the what can be conveyed to the computer.

The second relates more to human understanding in both reading and writing, though the degree to which it does so, differs a lot between uses, since they are informal and as such are not rigourously defined.

For instance, if we took a language like JavaScript and imposed a weird restriction on variable names, such as variable must be an 8-digit number preceded by an underscore, matching /^_[0-9]{8}$/, would we lose expressive power?

By the formal definition, we've lost no expressive power: We're restricted to 100,000,000 variables, but if we really needed to we could get around this by creating objects to hold more variables within the newly-created namespace. As such any program written in javascript today could be rewritten in this new form, so they are equally expressive.

By the informal definition, we've lost some, but just how much depends on just how informal we're being, which will vary because again you can't say what is "the rule" about an informl use. We might say we've lost a tiny amount, because programs with more than 100,000,000 variables in the same namespace have to be rewritten beyond a simple substitution. An even more informal use again would refer to the mental impact of such ungainly variable names on human comprehensive.

Its also worth noting that people will informally consider things that are not strictly part of the language at all. Consider the changes in Javascript from its creation until today.

By the most formal definition, there has been pretty unchanged in expressiveness; it was Turing complete to start with, after all.

By a more informal definition, it has become considerably more expressive in certain things like array manipulation, exception handling and (perhaps most of all) in the inclusion of regular expressions. These don't do anything that couldn't be done in javascript before, though they can often do something in a few lines and a subsecond execution time that would take kilobytes of code to write in javascript1.0 and a long time to run.

By a much more informal definition again, the change from javascript's first use in browsers (able to change the values of form inputs, document.write while the page is first being parsed and move to a new location or go back or forward in the history, but pretty much nothing else) to that today (able to change just about anything on the page, including on the basis of data from server calls) is absolutely immense, though most of it doesn't relate to javascript but to the object models and APIs made available, rather than the language (e.g. vbscript in IE benefitted from those changes equally).

To my mind, that last use is so informal as to not really be correct, but that's the problem with informal definitions.

By the formal defintion, it really hasn't become more expressive at all.


问:
Is there a clever way to calculate a mode of an online series without storing the series?
My program's aim is to determine the correct time zone offset (GMT+k) as a series of numbers are fed to it. eg:

-4
+11
1
-4
-4

So, here -4 (the mode of the series) is the correct value.  But this requires storing the series then analyzing it and I do not have enough storage (RAM and FLASH) for this.  The running average can be calculated easily by storing the list size and the sum.  Is there a similar case for finding the mode?

答:
To calculate the mode from an unreasonably large data set (or stream) containing only a finite number of discrete elements (such as integers in a small range), use a table to count the occurrence of each element, where the element in the data set is the key in our table. We then go through the data set and increment that element's counter. At any point we can then determine the mode of the processed part of the data set.

Pseudocode example

```<code> // all elements are integers in range a to b
 a = ...
 b = ...
 table = new Array(size: b - a, default: 0)

 // add items to the table
 for item in stream {
     table[item]++
 }

 // find the mode by sorting the table keys by their values
 mode = range(a, b).sortBy(item => table[item])
</code>```

Instead of an array, a general purpose Map type (e.g. a hash map) will be needed if the elements aren't integers.

Body:
To calculate the mode from an unreasonably large data set (or stream) containing only a finite number of discrete elements (such as integers in a small range), use a table to count the occurrence of each element, where the element in the data set is the key in our table. We then go through the data set and increment that element's counter. At any point we can then determine the mode of the processed part of the data set.

Pseudocode example

 // all elements are integers in range a to b
 a = ...
 b = ...
 table = new Array(size: b - a, default: 0)

 // add items to the table
 for item in stream {
     table[item]++
 }

 // find the mode by sorting the table keys by their values
 mode = range(a, b).sortBy(item => table[item])

Instead of an array, a general purpose Map type (e.g. a hash map) will be needed if the elements aren't integers.


问:
Parameterized Java Types (Generics)
Consider this "legacy" code:

```<code>public interface IPersistentCollection {
    IPersistentCollection cons(Object o);
}
</code>```

Genericized in Java, it could become something like this:

```<code>public interface IPersistentCollection<T> {
    IPersistentCollection<T> cons(T o);
}
</code>```

Clearly adding a new item to a mutable Java collection shouldn't change the type of the existing collection.  But unlike the Java collections, cons() returns a completely new, immutable collection, leaving the old collection unchanged, opening the possibility that it could meaningfully take on a different type than the original collection had.

Obviously, you should be able to cons an object of type Ford to a collection of Cars and get a collection of Cars back (covariance).  I think this is covered by the above generic example.

If Car and Train both extended a Vehicle class, it would be handy to be able to cons a Train to a collection of Cars and get a collection of Vehicles back (contravariance).  How would I even write that?  I thought by declaring new bounded type variables, S and E for "Vehicle" and "Train" in this example:

```<code>// Illegal because of <S super T>
<S super T, E extends S> IPersistentCollection<S> cons(E o);

// Simpler, but still Illegal because java disallows <S super T>
<S super T> IPersistentCollection<S> cons(S o);
</code>```

If we want to assume that the programmer knows what they are doing, you should be allowed to cons something totally unrelated to a collection and get a collection of Objects back.  I think this is the extreme case of contravariance, but I'm not sure there is even a name for it ("Dynamic Language" maybe?).

I think that if #2 were legal, it would cover cases #1 and #3.

My questions are:

A. To what degree is it possible to do #2 in Java?

B. Is #2 possible/easier in other languages?  Scala?  Haskell? ML?

C. In theory, a type system that preferred the most specific version of S in example 2 could handle a definition like this.  What book can I read about type systems without a PHD in math?  Is "Types and Programming Languages" by Pierce the best place to start?

Sample code would be appreciated.  If I'm using terms like covariance and contravariance incorrectly, I would appreciate being politely corrected.

答:
Scala's Lists work this way for the :: (cons) and ++ (concat) operators, but not for +, :+, and +: (which is okay because that's sometimes what you want).  The type signature looks like:

```<code>::[B >: T](x: B): List[B]

// Returns a List[Any] (Any is Scala's "Object" type)
5 :: List("example")
</code>```

This says B is a superclass of T, the type of the List you're consing onto.  You're consing a B element and returning a List of Bs.

Let's say T is a Car and B is a Vehicle.  The x parameter can be any subclass of Vehicle due to covariance, so you don't need to specify a third type.  I don't know Java's type system as well, but I imagine its equivalent (if it's supported) would be:

```<code><B super T> IPersistentCollection<B> cons(B o);
</code>```

Title: Parameterized Java Types (Generics)

Body:
Scala's Lists work this way for the :: (cons) and ++ (concat) operators, but not for +, :+, and +: (which is okay because that's sometimes what you want).  The type signature looks like:

::[B >: T](x: B): List[B]

// Returns a List[Any] (Any is Scala's "Object" type)
5 :: List("example")

This says B is a superclass of T, the type of the List you're consing onto.  You're consing a B element and returning a List of Bs.

Let's say T is a Car and B is a Vehicle.  The x parameter can be any subclass of Vehicle due to covariance, so you don't need to specify a third type.  I don't know Java's type system as well, but I imagine its equivalent (if it's supported) would be:

<B super T> IPersistentCollection<B> cons(B o);


问:
"Used with permission" reusable in a GPLv2 derivative work?
The LICENSE file of a GPLv2 application I am modifying contains a statement saying that certain resources used in the application were "used with permission" from 3rd parties - such as textual material from a published book and certain graphics.

Question:  in my derivative work based off of this application, am I required to seek permission from those 3rd parties to use those same resources?  Or does the GPLv2 encompass the fact that the use of these resources was already permitted in the original work, and thus the 3rd-party permission "flows through" to my derivative work?

答:
"With permission" can mean anything. It can mean "Permission to license under GPLv2" or "Permission for me to distribute them together with my GPLv2 application, but not for anyone else". When the license file doesn't make clear what kind of permission the author has, it isn't clear which license these resources are under. You should contact the author.

When the assets are not GPL and the application does not work without these assets, the GPLv2 is void and the author should choose a different license. Section 7 of the GPLv2 says:

If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all.


答:
The mode is the most commonly occurring single value. Fairly obviously, you just have to count occurrences of each value as it arrives and then at the end search the counts to find the largest. There are some interesting variations.

If and only if (a) the values are integers (b) you know the range in advance (c) you know the upper bound of the count then you can preallocate an array of suitable integers to hold the counts. That is probably the case in your particular situation.

If (b) is not true you can allocate an array and be prepared to resize it on the fly.

If (a) is not true you can use a hashed array (dictionary, map, etc) in much the same way, for some performance cost.

If (c) is not true (counts could exceed the range of int), you need to be prepared to allocate a second duplicate array to hold the overflows. And a third, and so on.

One final tweak. If you remember the value and highest count each time you update the array then you can avoid the final search.

Title: Is there a clever way to calculate a mode of an online series without storing the series?

Body:
My program's aim is to determine the correct time zone offset (GMT+k) as a series of numbers are fed to it. eg:

-4
+11
1
-4
-4

So, here -4 (the mode of the series) is the correct value.  But this requires storing the series then analyzing it and I do not have enough storage (RAM and FLASH) for this.  The running average can be calculated easily by storing the list size and the sum.  Is there a similar case for finding the mode?


答: How often will a value be repeated?  If the answer is "rarely", you may be better off storing the entire series, as the various Map / counter options probably use more memory.  Only when there is a fair amount of repeats are they an advantage.</p>


答: You received the application under the distribution terms of GPLv2.  Those are the only terms that apply to you.  If the party who gave it to you didn't have the right to distribute some of it, that's their problem, not yours.  Your responsibility is to honor the GPL restrictions, plus any other restrictions laid upon you in the license you received.  As long as the license doesn't restrict your use of those files, they're covered by the GPL.</p>

Title: "Used with permission" reusable in a GPLv2 derivative work?

Body:
The LICENSE file of a GPLv2 application I am modifying contains a statement saying that certain resources used in the application were "used with permission" from 3rd parties - such as textual material from a published book and certain graphics.

Question:  in my derivative work based off of this application, am I required to seek permission from those 3rd parties to use those same resources?  Or does the GPLv2 encompass the fact that the use of these resources was already permitted in the original work, and thus the 3rd-party permission "flows through" to my derivative work?


答:
Basically it's nature and easy to spell, remember! Look at Java, i feel it seems that's English, not programming language ;)!
BTW, if you look at Python or Ruby, you will see something really short!</p>

Title: Long Keywords like `function` and `namespace`

Body:
In many English-based programming languages like C++ and JavaScript, there exist long keywords like function, namespace, exception (in OCaml languages) and such. Do you think shorter keywords like func should replace them? Why or why not? What about replacing them with digraph operators?

The long keywords we will be mainly talking about, but not limited to, are mainly from curly-brace imperative languages: function, namespace, implements, instanceof and synchronized (I always misspell that).
You should also show the examples from your favourite programming language.


问:
"Ever change the value of 4?" - how did this come into Hayes-Thomas quiz?
In 1989 Felix Lee, John Hayes and Angela Thomas wrote a Hacker's test taking the form of a quiz with many insider jokes, as “Do you eat slime-molds?”

I am considering the following series:

```<code>0015 Ever change the value of 4?
0016 ... Unintentionally?
0017 ... In a language other than Fortran?
</code>```

Is there a particular anecdote making the number “4” particular in the series?

Did some Fortran implementation allow to modify the value of constants?  Was this possible in other languages in common use at that time?

答:
It was an unintentional side effect of FORTRAN's function call evaluation strategy in combination with an erroneous compiler optimization.

FORTRAN II introduced user-defined functions and subroutines with their arguments passed by reference.  (Why, I don't know.  It was probably more efficient than pass-by-value on IBM hardware of the time.)

Normally, pass-by-reference means you have to have to pass an l-value (like a variable) instead of an r-value.  But the designers of FORTRAN decided to be helpful and let you pass r-values as arguments anyway.  The compiler would automatically generate a variable for you.  So, if you wrote:

```<code>CALL SUBFOO(X + Y, 4)
</code>```

the compiler would convert this behind the scenes to something like

```<code>TEMP1 = X + Y
TEMP2 = 4
CALL SUBFOO(TEMP1, TEMP2)
</code>```

There was also a common compiler optimization called a “literal pool”, that would consolidate multiple instances of the same numeric constant into the same auto-generated variable.  (Several languages in the C family require this for string literals.)  So, if you wrote

```<code>CALL SUBBAR(4)
CALL SUBBAZ(4)
</code>```

this would be treated as if it were

```<code>FOUR = 4
CALL SUBBAR(FOUR)
CALL SUBBAZ(FOUR)
</code>```

which seems like a perfectly reasonable thing to do until you have a subprogram that changes the value of its parameters.

```<code>SUBROUTINE SUBBAR(X)
    !...lots of code...
    X = 5
    !...lots of code...
END SUBROUTINE SUBBAR
</code>```

Boom! CALL SUBBAR(4) changed the value of the 4 in the literal pool to a 5.  And then you're left wondering why SUBBAZ is assuming you passed it a 5 instead of the 4 you actually wrote in the code.

Newer versions of Fortran mitigate this problem by letting you declare the INTENT of a variable as IN or OUT, and giving you an error (or at least a warning) if you pass a constant as an OUT parameter.

Body:
It was an unintentional side effect of FORTRAN's function call evaluation strategy in combination with an erroneous compiler optimization.

FORTRAN II introduced user-defined functions and subroutines with their arguments passed by reference.  (Why, I don't know.  It was probably more efficient than pass-by-value on IBM hardware of the time.)

Normally, pass-by-reference means you have to have to pass an l-value (like a variable) instead of an r-value.  But the designers of FORTRAN decided to be helpful and let you pass r-values as arguments anyway.  The compiler would automatically generate a variable for you.  So, if you wrote:

CALL SUBFOO(X + Y, 4)

the compiler would convert this behind the scenes to something like

TEMP1 = X + Y
TEMP2 = 4
CALL SUBFOO(TEMP1, TEMP2)

There was also a common compiler optimization called a “literal pool”, that would consolidate multiple instances of the same numeric constant into the same auto-generated variable.  (Several languages in the C family require this for string literals.)  So, if you wrote

CALL SUBBAR(4)
CALL SUBBAZ(4)

this would be treated as if it were

FOUR = 4
CALL SUBBAR(FOUR)
CALL SUBBAZ(FOUR)

which seems like a perfectly reasonable thing to do until you have a subprogram that changes the value of its parameters.

SUBROUTINE SUBBAR(X)
    !...lots of code...
    X = 5
    !...lots of code...
END SUBROUTINE SUBBAR

Boom! CALL SUBBAR(4) changed the value of the 4 in the literal pool to a 5.  And then you're left wondering why SUBBAZ is assuming you passed it a 5 instead of the 4 you actually wrote in the code.

Newer versions of Fortran mitigate this problem by letting you declare the INTENT of a variable as IN or OUT, and giving you an error (or at least a warning) if you pass a constant as an OUT parameter.


问:
How to set more accurate "deadlines"?
Context:

My work is to build financial reports using mostly Excel spreadsheets. This consists mostly of formulas and a good deal of VBA. Each person is built by a single person. We service many sub-departments under the finance / accounting department and we often have many projects lined-up. I have had a rough time in the last few months because of projects taking longer than expected, then projects overlapping and getting very close to critical deadlines.

Question:

Obviously, we try our best to plan our projects so that we have a little bit of room to breathe but I always feel helpless when I have to estimate how long a given project will take me to complete. Are there techniques that can be used to better estimate how long a project can take to complete ?

Analysis:

I am thinking that one way to get a better idea of the length of the project would be to look into our process for getting requirements which could be infinitely better. It would help to get a clearer picture but it would still not give us a measurement. Then I thought that maybe isolating and measuring the average development time of different tasks that need to be done for most reports (e.g. build the queries, write the functions, construct the report, automate the process) would be one way to achieve this but it does not take into account the variability in complexity of those tasks. Some reports have very simple queries while others are extremely complex. Obviously the more complex the query the longer it would take.

Note:

Most of the time we have to deal with legacy code / inefficient reports which can cloud the waters even more.

答:
>Are there techniques that can be used to better estimate how long a project can take to complete ?

The problems that you are having aren't due to your estimating ability at all. The issue is that your estimates are becoming deadlines.

Repeat after me, and repeat in front of your client. Estimates are just that, estimates.

What happens is that estimates become solid. When you say "It'll probably take 2 weeks", people figure that it will be done and finished in two weeks.

What you need to do is periodically update your estimates and actualities, and effectively communicate them with the rest of the business. If something takes an extra week, you need to push everything back by a week. Either that, or drop something, or re-prioritise.

Title: How to set more accurate "deadlines"?


问:
What are the disadvantages of a "simple factory"?
I am reading the book »Head First Design Patterns« from O'Reilly. Before explaining the Factory Method Pattern, they introduce a Simple Factory first.

They are using the example of a pizzeria. In a first step they show the problem:

```<code>Pizza orderPizza(string type) {
  Pizza pizza;
  if (type.equals("Pepperoni") { pizza = new PepperoniPizza(); }
  else if (type.equals("Salmon") { pizza = new SalmonPizza(); }
  // ... and so on

  pizza.Prepare();
  pizza.Bake();
  pizza.Cut();
  pizza.Pack();
  return pizza;
}
</code>```

The obvious problem is that you had to change Pizzeria whenever you add or remove a Pizza.

Hence they introduce a "Simple Factory Idiom" first. They move the creating part into a class "SimplePizzaFactory". Now you don't need to modify Pizzeria anymore when adding or removing a Pizza.

Then they say that this approach isn't that good, when you have more than one pizzeria (in several towns).

I don't really understand their reasoning. They give the following example code and then they say that each pizzeria wouldn't be using the procedure as implemented above but were using different methods in order to "bake", "cut" and "pack" the pizza.

```<code>BerlinPizzaFactory berlinFactory = new BerlinPizzaFactory();
Pizzeria berlinPizzeria = new Pizzeria(berlinFactory);
berlinPizza.Order("Pepperoni");
</code>```

Instead of using the Simple Factory, they suggest using the Factory Method Pattern.

First, I don't see why the BerlinPizzeria is supposed to not using the procedure. It's still a Pizzeria and when you call Order, you're using the same procedure.

My best guess is that they are implying that you are able to implement, let's say, a cafeteria (I'm deliberately using something entirely different to make my point) and use the factory (as it is independent of the pizzeria) and prepare the pizza in a way you want to.

But even when using the Factory Method Pattern, nobody forces you to use the default procedure. It's even simpler to "hide" that you're doing it differently. Their code examples are given in Java and Java methods are virtual by default. So I would be able to implement BerlinPizzeria and override Order (or had to explicitly declare the method as final). The client, however, wouldn't notice that my BerlinPizzeria is doing things differently.

In conclusion I don't see any significant difference between a Simple Factory and the Factory Method Pattern. The only advantage of the Factory Method Pattern I'm seeing is that you would save a few classes (namely, the 'outsourced' factories).

So, what is really the disadvantages of a Simple Factory and why isn't is a good idea to 'outsource' the creating part?

Or what is really the advantage of the Factory Method pattern and why is it a good idea to force the creating part being implemented in the subclass?

答:
Let's have a look at the Simple Factory
The intention for the Simple Factory is straightforward: It produces instances of concrete classes. Sticking to your example: you have a Pizzeria with methods like order():

```<code>public enum Pizzas {
    QUADDROSTAGGIONI, SALMONE, ROMANA
}

public class Pizzeria {
    public static Pizza order(Pizzas type){
        switch(type){
            case ROMANA: return new Romana();
            case SALMONE: return new Salmone();
            case QUADDROSTAGGIONI: return new Quaddrostaggioni();
            default: throw new NoRecipeException();
        }
    }

}
</code>```

This is really a simple case of a factory.
If you decide, that you wanted a Salmone-Pizza, you simply order an instance like this:

```<code>  Pizza salmone=Pizzeria.order(Pizzas.SALMONE);
</code>```

The advantage: you separated the use of Pizzas from its creation. You only want Pizza, independend of its creation process. You could enjoy Pizza without baking one yourself.

The downside: If you have several subtypes of the given flavours of Pizza (e.g. ROMANABerlinStyle, ROMANAHamburgStyle) you have two choices.

1) to add the new kind to the existing Pizzeria. That clutters your Pizzeria and you have to deal with several flavours, which aren't that different (e.g. ROMANABerlinStyle adds garlic and ROMANAHamburgStyle adds wild garlic) in one Pizzeria. Besides: it is of no advantage knowing, that you consume a berlinstyle or hamburgstyle pizza. You only wanted some well defined kind of Pizza from the Pizzeria.

2) you abstract one step further: you separate the individual flavours of the given kinds QUADDROSTAGGIONI, SALMONE, ROMANA into independend factories. That means, the BerlinPizzeria knows its recipe and so does the HamburgPizzeria.

You are now allowed to have many different Pizzerias which could have their own recipes:

The traditional Pizzeria from above

```<code>public class PizzeriaImpl implements Pizzeria {

    public Pizza order(Pizzas type){
        switch(type){
            case ROMANA: return new Romana();
            case SALMONE: return new Salmone();
            case QUADDROSTAGGIONI: return new Quaddrostaggioni();
            default: throw new NoRecipeException();
        }
    }

}
</code>```

and a berlinstyle one

```<code>public class BerlinPizzeriaImpl implements Pizzeria{

    public Pizza order(Pizzas type){
        switch(type){
            case ROMANA: return new BerlinRomana();
            case SALMONE: return new BerlinSalmone();
            case QUADDROSTAGGIONI: return new Quaddrostaggioni();
            default: throw new NoRecipeException();
        }
    }

}
</code>```

Now you are able to start out your franchise:

```<code>public class PizzaFranchiseImpl implements Pizzeria{

    Pizzeria p;

    public  Pizza order(Pizzas type){
        return p.order(type);
    }

    public PizzaFranchiseImpl(Pizzeria p){
        this.p=p;
    };

}
</code>```

If you are in Berlin you simply inject your BerlinPizzeriaImpl.

The advantage: you are free to decide which flavour you support in each city (BerlinRomana, BerlinSalmone, traditional Quadrostaggioni). And this is completely transparent to your customer/consumer.

This follows the OpenClosed-principle: Your Pizzeria is closed, as you have a fixed set of pizzas, which you deliver (QUADDROSTAGGIONI, SALMONE, ROMANA), but you are open for new flavours, e.g. berlinstyle.

Further: each pizzeria itself is devoted to one style of pizza. The BerlinPizzeriaImpl doesn't care how to do a traditional Romana (Single Responsibilty Principle).

Last but not least, you decouple different pizza styles from the franchise. The franchise needs only to know how to handle orders.

EDIT: I substituted the dead body with a delicious but dead fish :D

Body:
Let's have a look at the Simple Factory
The intention for the Simple Factory is straightforward: It produces instances of concrete classes. Sticking to your example: you have a Pizzeria with methods like order():

public enum Pizzas {
    QUADDROSTAGGIONI, SALMONE, ROMANA
}

public class Pizzeria {
    public static Pizza order(Pizzas type){
        switch(type){
            case ROMANA: return new Romana();
            case SALMONE: return new Salmone();
            case QUADDROSTAGGIONI: return new Quaddrostaggioni();
            default: throw new NoRecipeException();
        }
    }

}

This is really a simple case of a factory.
If you decide, that you wanted a Salmone-Pizza, you simply order an instance like this:

  Pizza salmone=Pizzeria.order(Pizzas.SALMONE);

The advantage: you separated the use of Pizzas from its creation. You only want Pizza, independend of its creation process. You could enjoy Pizza without baking one yourself.

The downside: If you have several subtypes of the given flavours of Pizza (e.g. ROMANABerlinStyle, ROMANAHamburgStyle) you have two choices.

1) to add the new kind to the existing Pizzeria. That clutters your Pizzeria and you have to deal with several flavours, which aren't that different (e.g. ROMANABerlinStyle adds garlic and ROMANAHamburgStyle adds wild garlic) in one Pizzeria. Besides: it is of no advantage knowing, that you consume a berlinstyle or hamburgstyle pizza. You only wanted some well defined kind of Pizza from the Pizzeria.

2) you abstract one step further: you separate the individual flavours of the given kinds QUADDROSTAGGIONI, SALMONE, ROMANA into independend factories. That means, the BerlinPizzeria knows its recipe and so does the HamburgPizzeria.

You are now allowed to have many different Pizzerias which could have their own recipes:

The traditional Pizzeria from above

public class PizzeriaImpl implements Pizzeria {

    public Pizza order(Pizzas type){
        switch(type){
            case ROMANA: return new Romana();
            case SALMONE: return new Salmone();
            case QUADDROSTAGGIONI: return new Quaddrostaggioni();
            default: throw new NoRecipeException();
        }
    }

}

and a berlinstyle one

public class BerlinPizzeriaImpl implements Pizzeria{

    public Pizza order(Pizzas type){
        switch(type){
            case ROMANA: return new BerlinRomana();
            case SALMONE: return new BerlinSalmone();
            case QUADDROSTAGGIONI: return new Quaddrostaggioni();
            default: throw new NoRecipeException();
        }
    }

}

Now you are able to start out your franchise:

public class PizzaFranchiseImpl implements Pizzeria{

    Pizzeria p;

    public  Pizza order(Pizzas type){
        return p.order(type);
    }

    public PizzaFranchiseImpl(Pizzeria p){
        this.p=p;
    };

}

If you are in Berlin you simply inject your BerlinPizzeriaImpl.

The advantage: you are free to decide which flavour you support in each city (BerlinRomana, BerlinSalmone, traditional Quadrostaggioni). And this is completely transparent to your customer/consumer.

This follows the OpenClosed-principle: Your Pizzeria is closed, as you have a fixed set of pizzas, which you deliver (QUADDROSTAGGIONI, SALMONE, ROMANA), but you are open for new flavours, e.g. berlinstyle.

Further: each pizzeria itself is devoted to one style of pizza. The BerlinPizzeriaImpl doesn't care how to do a traditional Romana (Single Responsibilty Principle).

Last but not least, you decouple different pizza styles from the franchise. The franchise needs only to know how to handle orders.

EDIT: I substituted the dead body with a delicious but dead fish :D


答:
Establish Due Date Risk It doesn't sound like you're communicating the accuracy (or lack of it) of your estimations nor are you getting complete user expectations. Ask when they need it and why. You tell someone you can finish by Friday and they say, "Great." There is a chance you are off by 1-3 days and what you don't know, is they have to give the report to some regulatory agency on Monday or pay a penalty. This is a very high risk situation. A lesser one may be promising a client they'll get their report on Monday. Nobody want to have to call the client back with bad news.

Estimate in Smaller Pieces With reporting, I find you get better requirements after you the user can see some raw data (Can we add another column?). I'm usually pretty accurate when I can deliver this and they know they need to give me some feedback in a timely manner or the over-all creating of the report is going to get delayed. Also, there may be some very complex features that can be omitted because of time constraints. It's up to the user if they are willing to wait.

Managing How Long it Takes Versus How Long You Have Let's say you accurately estimated a report will take 8 hour and since you received the request first thing this morning, you promise to have it done by the end of the day. The only problem is you cannot commit the full day to this report because something came up. You can keep using your technique and tell the user it will take 10 hours ( +2 hours of "breathing" room) or you can let them know this estimate is contingent on nothing else coming up. When something comes up, just let them know it is going to be delayed.

It is very important to communicate. I recently had a home remodeling project go from a 2-3 day estimate to 5. Nobody bothered to tell me one of the key carpenter's wife was having a baby, so he was going back and forth to the hospital. Software takes such a bad rap for delayed projects, but I'm not convinced other industries are much better.

Title: How to set more accurate "deadlines"?

Body:
Context:

My work is to build financial reports using mostly Excel spreadsheets. This consists mostly of formulas and a good deal of VBA. Each person is built by a single person. We service many sub-departments under the finance / accounting department and we often have many projects lined-up. I have had a rough time in the last few months because of projects taking longer than expected, then projects overlapping and getting very close to critical deadlines.

Question:

Obviously, we try our best to plan our projects so that we have a little bit of room to breathe but I always feel helpless when I have to estimate how long a given project will take me to complete. Are there techniques that can be used to better estimate how long a project can take to complete ?

Analysis:

I am thinking that one way to get a better idea of the length of the project would be to look into our process for getting requirements which could be infinitely better. It would help to get a clearer picture but it would still not give us a measurement. Then I thought that maybe isolating and measuring the average development time of different tasks that need to be done for most reports (e.g. build the queries, write the functions, construct the report, automate the process) would be one way to achieve this but it does not take into account the variability in complexity of those tasks. Some reports have very simple queries while others are extremely complex. Obviously the more complex the query the longer it would take.

Note:

Most of the time we have to deal with legacy code / inefficient reports which can cloud the waters even more.


问:
Is it anti-pattern to mix unit test and web test?
It is a language agnostic question, e.g. I have a unit test like

```<code># Unit test
User user = User.create('john');
assertEquals("User name is john", "john", user.getName());

# Web test start from here
goTo("/user/john");
assertTitleEquals("john");
</code>```

Do you think it is an anti-pattern?
Although I can write a full selenium test suites to do the same thing, but using the above code save much of my time (e.g. no more click('Login'); waitUntil etc, and I don't need to worry if my UI is changed at all, sound like it is a quick and more stable approach to test?

答:
That's not a unit test; it's an acceptance test. I think a few people are getting hung up on that fact that you called it a unit test without looking at what you're actually trying to achieve.

It looks as if what you're doing in the first set of steps is using perfectly decent code which happens to come from a unit testing framework to set up a context. That is, something like:

Given John is registered as a user

If you were doing BDD, or using a BDD framework, that would be your step. It wouldn't matter how the context was set up, because what we're really interested in is the outcome:

Then John's title should be "John".

This should be true regardless of how the context was created. Creating the context by hitting the database or using a service or any other mechanism is OK. If you ever feel the need to check that the user-creation pages work OK, make them into a separate scenario (or test).

Your test is therefore just fine, because what you're doing is a system-level test (or acceptance test if you like), not a unit test (even though you're using unit-testing code inside it).

The assertion that John's registration exists might be redundant, but is useful if you want to check that your context has been set up successfully (for instance, the database hasn't got out of sync with that User.create call) without having to wait for the next steps in the test to fail.

You might also want to put some abstractions around the steps, just to keep them maintainable. You could use the English Language BDD frameworks, or more maintainably, create a nice little DSL like this. It's also worth having a look at the Page Object pattern. This will keep your context-setup clean, and make it much easier to change it later on if you decide to do something different.

The equivalent to unit-testing's "only one reason to fail" in system-level tests is "only one aspect of behaviour", which is the same thing, only at a higher level of abstraction.

Don't forget that class-level TDD is also very valuable!


问:
Is this a good design in C++?
Is it a good idea to replace getters and setters with a single function returning a reference?
For example, instead of this,

```<code>class Person {
  std::string name;
public:
  std::string GetName() { return this->name; }
  void SetName(std::string& toSet) { this->name = toSet; }
};
</code>```

Is this a good idea,

```<code>class Person {
  std::string name;
public:
  std::string& Name() { return this->name; }
};
...
...
Person p;
p.Name() = "Joe"; // Write.
std::string local = p.Name(); // Read.
</code>```

Does the second code have some problem?

But in C#, methods return object by reference. For example,

```<code>class Person
{
    string name;
    public Person(string _name) { this.name = _name;  }
    public string GetName()
    {
        return this.name;
    }
    public void SetName(string _name)
    {
        this.name = _name;
    }
};

class Company
{
    Person manager;
    public Company()
    {
        this.manager = new Person("Mr. K");
    }

    // The Person object is returned by reference.
    // This is equivalent to "Person& GetManager()" in C++.
    public Person GetManager()
    {
        return this.manager;
    }
};
...
...
Company comp = new Company();

// Equivalent to,
// Person& p = comp.GetManager();
Person p = comp.GetManager(); // p is a reference to comp.manager
p.SetName("Mr. L");  // This statement changes comp.manager.name

Console.WriteLine(comp.GetManager().GetName()); // Prints "Mr. L"
</code>```

In the above code, comp.manager.name wouldn't have changed if the method GetManager() returned Person by value. So, this code isn't dependent on return value optimization.
Isn't this code a violation of encapsulation?

答:
The second code is conceptually the same as providing public access to the member variable.

It also has the exact same drawbacks: You can't change your mind on how a person's name will be stored and you can't control how the property will be used.

You can't change the implementation, because to return a reference, you need an actual std::string object to return that remains valid.

In other words, by returning a reference, you are breaking encapsulation.

If you are worried about the efficiency of returning by value, the large majority of modern compilers implemet RVO (return value optimisation) and will heavily optimize returning stuff by value to avoid making copies that will be destructed immediately thereafter.

If you are using a compiler that doesn't have RVO, you can return a const reference. That doesn't give the same drawback, because the user of your class can't use such a reference to change your internals.

Also, if you find that you need to change how stuff is stored internally in the class, you can change the return type to returning a value without (significantly) affecting the users of the class.

Title: Is this a good design in C++?


问:
Efficiency of getters/setters with database performance
I'm currently in the process of refactoring a very old personal project of mine, which used procedural PHP-in-HTML code. I'm modernising it as a learning project, using OOP where beneficial. I understand the basics of OOP but I'm wondering if I understand correctly as it would seem my old way of doing this was faster in this case.

On a user's profile page, all of their stats are listed. It's a game so there are lots of individual fields containing stats like wins, losses etc.

Now I've made a User class and given every stat its own getter/setter. A typical pair looks like this:

```<code>function getEmoticon() {
    if ($this->emoticon) {
        return $this->emoticon;
    }

    $stmt = $this->conn->prepare('SELECT emoticon FROM profile WHERE id=:userid');
    $stmt->execute(array('userid' => $this->userid));
    $row = $stmt->fetch();

    return $this->emoticon = $row['emoticon'];
}

function setEmoticon($emoticon) {
    $stmt = $this->conn->prepare('UPDATE profile SET emoticon=:emoticon WHERE id= :id');
    $stmt->execute(array('id' => $this->userid, 'emoticon' => $emoticon));
    return $this->emoticon = $emoticon;
}
</code>```

There used to be one single "GET * FROM profile" SQL query to get all the user's stats in a single query. Now though, I'm resorting to using the getter for every stat, resulting in a database query for every stat. On the profile page it means it has gone from 1 database query to dozens.

Is this the right way to do things? It seems more inefficient but I'm not sure how else to do it, unless I have a User class method like getAllStats() or something.

答:
Yeah, don't do that.

A typical approach would be to have a LoadUser($user_id) function. It will return a user with all its attributes loaded from the database. Hence, load all the attributes of the object when you first create it, don't try to lazily load each attribute one at a time. It will be simpler and more efficient.

When you want to save it, either have a Save(), or keep track of all the objects that have been modified and them save them all at once.

As a general rule, be suspicious of lazy loading like this. I find that it 90% of cases its better just to load the data up front.