问:
Any point in using ES6 Map when keys are all strings?
Plain object keys must be strings, whereas a Map can have keys of any type.

But I have little use for this in practice. In nearly all cases, I find myself using strings as keys anyway. And presumably new Map() is slower than {}. So is there any other reason why it might be better to use a Map instead of a plain object?

答:
There are some reasons why I prefer using Maps over plain objects ({}) for storing runtime data (caches, etc):

The .size property lets me know how many entries exist in this Map;

The various utility methods - .clear(), .forEach(), etc;

They provide me iterators by default!

Every other case, like passing function arguments, storing configurations and etc, are all written using plain objects.

Also, remember: Don't try to optimize your code too early. Don't waste your time doing benchmarks of plain object vs Maps unless your project is suffering performance problems.


问:
Why dynamic memory allocation functions in C returns void*?
Consider the prototypes of C's dynamic allocation functions

```<code>malloc - void* malloc(size_t size);

calloc -  void* calloc(size_t n,size);

realloc - void* realloc(void* ptr,size_t newsize);
</code>```

Now a statement like following

```<code>int* p=(int*)malloc(sizeof(int));
</code>```

I know that casting to (int*) isn't needed in C since a void pointer can be assigned to a pointer variable of any object type, but why these functions by default not return fully typed pointer?. Wouln't it be nice if it returns int* instead of void pointer in this case? What is the reason void* is choosen as return type of these functions?

One other question: I've read here that in older C compilers the type of pointer returned by these functions was char* not void*. Is it true?

答: Of course malloc() could return a fully typed pointer.  The problem is, of what type?  If it returned an int*, it would make you happy, but it would not make me happy, because I want a char* instead.  Clearly, we could not both have it our way.  So, void* is a good baseline which does not take anyone's side.

ContentLicense: CC BY-SA 3.0


问:
When I modify and redestributes software that is originally using the MIT License, can I revoke the right to sell my modification?
There is a piece of software, free, and open source, under the MIT License.

I make modifications to it, make it better, etc. I distribute this new software, also for free and open source.

But can I revoke from those that use my new version the right to sell? I'm not ever going to sell my modified software; it will always be free and open source. That said, I don't want others to take my source, and scam others by selling it at a price.

答:
The MIT license allows relicensing of the material and does not require that it be under the MIT license.

Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions

As described in What "sublicense" actually means? this means that you may incorporate your work and release it under a more restrictive license. In this case, removing the ability to sell copies of the software.  That that with a significant grain of IANAL.

However, there's a bit 'gotcha' in this.  The right to sell is part of the open source definition (and gnu philosophy).

The license must not restrict anyone from making use of the program in a specific field of endeavor. For example, it may not restrict the program from being used in a business, or from being used for genetic research.

As your modification would restrict a field of endeavor, it wouldn't be open source, nor compatible with other open source products which may lead to other difficulties.

But yes, you may relicense it anyway you want.  The MIT is not a viral license and you can even take the entire project closed source if you so desire.  But remember, that removing the right to sell is no longer free and open source.  Your code could not be used in a GPL project, nor any other open source project with that restriction.


问:
Do I need to estimate maintenance software issues?
The PM of the company I work on, always asks me to estimate maintenance issues and since there are several legacy systems that I didn't build, makes this hard to get.
He says getting estimations for every task is necessary to have a clear plan, since I'm involved in projects and maintenance tasks.

Do you guys have the same problem?

答:
It's not difficult to make these estimates, it's just a lot of work and it you just need time. So the first estimate is that you need a day to find all the source files and to find out how many there are. Once you have all the source files and know how many there are, you can make an estimate how long it will take you to examine all the source files and create good estimates for maintenance issues. That's probably a few weeks. Notice that that's the time you need to make reasonable estimates, not the time to do any useful work.

So if your PM gives you that time to provide the estimates, then you are fine.

Or you just use brute force: If there is a system that you have never touched, but there are people around who know that system, and they can be interviewed, estimate 3 days to find your way around that system. If nobody is around who knows the system, take 6 days. If there is documentation how to build and deploy the system, add two days for building and deploying (because that documentation is surely out of date), else add five days. Two days for a bug fix, five days for a small improvemnt, 10 days for a large improvement.

Create a table of estimates and actual time to do the job. Once you've done a few jobs, use that data to fine tune your estimates. And always state very forcefully that these are estimates, and reality is stronger than estimates.


问:
Handling if-statements with a known duration
I wasn't sure exactly what to call these situations, so I'll illustrate it.

If I have something like this in a method:

```<code>if (i <= 5)
    doSomething();
else
    doSomethingElse();
</code>```

but I know that i will never be less than or equal to 5 once it exceeds 5, it becomes unnecessary to continue checking the if-statement once it branches off the first time.

Is it a good idea to implement a strategy pattern in this case, to avoid redundant checks?

```<code>class strategy1 implements strategy {

    Object obj; // stores a reference to the object that uses it

    void run() {
       if (i <= 5)
            doSomething();
        else {
            obj.strategy = new strategy2(obj);
            obj.strategy.run();
        }
    }
}

class strategy2 implements strategy {

    void run() {
        doSomethingElse();
    }

}
</code>```

and the object simply calls strategy.run()

I feel like this sacrifices some readability and simplicity for performance, but it also makes it clear that i will not fall below 6 once it hits 6, which provides some more information than the if-statement alone did. Is there a better way?

答:
The simplest code doing the job is the best.

The first version just works. And it is very simple: All it has to do is to evaluate which of two functions to call, and then to call the right one. Little chance of error. Trivial to change if the determination what to call changes.

Now you are making things complicated. You assume that once the second function has been called, the condition will never be such that the first function should be called again. That's a big assumption, and "never" is a very long time. How much will you kick yourself if it turns out that i can be reset to 1, and your code breaks, and the only way to fix it is to remove your clever code and reintroduce the simple check? How much will I want to kick you if your clever code leads to this bug, and it's my job to fix it?


答:
I will approach it from different side of things - in this case you will get the advantage of branch prediction. If you say you have a sorted sequence, this should be ideal in your case.

The idea is your original if statement will be extremely fast before the crossover and shortly after. So, chances are it will be faster than actually having logic around it.

The way branch prediction works, is your processor would try to guess the outcome of the statement base don the past outcomes and preload the following statements accordingly. If you sequence is sorted, your processor would be correct 99.9999% of the time except a couple times after the crossover, which actually gains you speed.

Title: Handling if-statements with a known duration

Body:
I wasn't sure exactly what to call these situations, so I'll illustrate it.

If I have something like this in a method:

```<code>if (i <= 5)
    doSomething();
else
    doSomethingElse();
</code>```

but I know that i will never be less than or equal to 5 once it exceeds 5, it becomes unnecessary to continue checking the if-statement once it branches off the first time.

Is it a good idea to implement a strategy pattern in this case, to avoid redundant checks?

```<code>class strategy1 implements strategy {

    Object obj; // stores a reference to the object that uses it

    void run() {
       if (i <= 5)
            doSomething();
        else {
            obj.strategy = new strategy2(obj);
            obj.strategy.run();
        }
    }
}

class strategy2 implements strategy {

    void run() {
        doSomethingElse();
    }

}
</code>```

and the object simply calls strategy.run()

I feel like this sacrifices some readability and simplicity for performance, but it also makes it clear that i will not fall below 6 once it hits 6, which provides some more information than the if-statement alone did. Is there a better way?


问:
Why is modularity a good idea?
I have a programmer on my team who wants to take all the control flow logic for handling events sent by any module and put it all in a single file, because they think it will make an already-complex system easier to maintain and grow. How can I convince them that this is a bad idea?

Sources to reading material are welcome, as well as general arguments. Arguments for the idea are also welcome.*

Here's what I've got so far:

The single file will become a merge nightmare, since adding any module will require adding logic to the central controller. If two engineers add two different features, one will have to resolve the conflicts in the central file.

The central controller file will get excessively long, growing at least linearly with the number of modules, if not N2 with the with the number of interactions between different modules.

Any message handling logic that accesses internal state for a given module will either need to be wrapped in a function (this is not necessarily bad), or have its module expose that state (this is bad).

The central controller will be highly coupled—since it will have a dependency on every other module in the system—and have very little cohesion, with the blocks of logic only related because they're caused by any two modules interacting together.

The dependencies between different modules will not be explicit, since a single controller will be responsible for handling those interactions.

Writing unit tests for each module, or integration tests between two modules will be impossible without pulling in every other module via the central controller. The central controller itself will be pretty much untestable, outside of end-to-end testing.

* Implementing a state machine to control the flow of a system is not necessarily a bad idea, but different parts of the program still need to be modularized and not have to care about states or state transitions that don't matter to them.

答:
There is an anti-pattern - God Object.

Just like you stated, God Objects:

are hard to maintain

usually violate one or many SOLID principles.

impossible to understand for new developers

hard to locate functionality in for new developers

do not describe system at first glance at file structure

etc.

Having module controller is quite OK actually, something should have knowledge of all the modules, however, the only responsibility of such a class should be providing modules for its users.

Anything specific to  a module should be inside the module and have nothing to do with this class.

Common practice is to write such a class once and provide a list file(xml, json, etc...) with modules. As modules are added to the system, the main Module Controller doesn't change, because it was decoupled enough from the modules in the first place.

Title: Why is modularity a good idea?


问:
Who should be responsible for syncing a repository?
Given an app, controller, model and repository (which holds representation of model), where should the sync service for the repository live?

In my specific implementation, my app/controller are AngularJS, models are generic JS and repository is a repository/datastore containing a representation of the data from model. The repository currently has some PouchDB code within it (set local and remote repo addresses; sync handler).

I'm assuming the sync code will be clearer/easier to work with if it exists in its own sync service or if I move it out of the repository and into the controller...

Should the repository class be responsible for syncing itself?

答:
Depends what you mean by synching.
Usually, a repository is used by controllers. So Controller is the one to draw from it and to place data back. Also, controller triggers methods like .save(), that in turn would be implemented by repository and will push data to persistence layer(PouchDB) in your case.


问:
C++ design for encoder/decoder classes with different stored types
I need to handle different elements in a vector, each element owning a specific parameter (integer or string), so that I can easily handle encoding/decoding of a series of elements.

Encoding a list of elements serializes the elements, inserting a separator in-between each.

Decoding a string consists in finding the separators then for each substring, extracting the ID and type-specific value. Example (knowing that "FOO" is associated to an integer and "BAR" is associated to a string): "FOO=54,BAR=hello" gives {{ID_FOO, 54}, {ID_BAR, "hello"}} .

I have the current following bare design:

```<code>#include <cstdint>
#include <cstdlib>
#include <string>
#include <memory>

enum eID { /*...*/ };

// Base class
class Base {
private:
    enum eID m_Id;
public:
    Base(enum eID = 0): m_Id(eID) {}
    virtual std::string Encode() {
        // Return encoding of m_Id
    }
    static Base* Decode(const std::string &str) {
        Base *ptr;
        // Extract id
        // According to the kind of id, create a new Derived<T>
        // giving the substring to the constructor
        // ptr = new Derived<...>(id, str.substr(...));
        return ptr;
    }
};

template <class T>
class Derived<T> : public Base {
private:
    T m_Value;
public:
    Derived(enum eID id, const std::string &str); // participates to decoding
    std::string Encode();
};

template<>
Derived<std::string>::Derived(enum eID id, const std::string &str) {
    m_Value = str; // easy
}

template<>
std::string Derived<std::string>::Encode() {
    return static_cast<Base*>(this)->Encode() + m_Value;
}

template<>
Derived<long>::Derived(enum eID id, const std::string &str) {
    m_Value = strtol(str.c_str(), nullptr, 10);
}

template<>
std::string Derived<long>::Encode() {
    // Encode id and integer param to a string
}

class BaseList {
private:
    std::vector<std::unique_ptr<Base>> m_List;
public:
    void Append(Base *ptr) {
        m_List.push_back(std::unique_ptr<Base>(ptr));
    }
    std::string Encode() {
        // Call each Encode() function and concatenate strings together
        // Insert a delimiter in-between substrings
    }
    void Decode(const std::string &sToDecode) {
        // Look for delimiters in sToDecode
        // For each delimited substring:
        // - call Base::Decode() to allocate a new type-specific object
        // - push back into m_List
    }
}
</code>```

(This is not be a complete compiling example.)

Is it a logic design? How could it be optimized so that it may match any existing design pattern(s)? In particular I am concerned with the decoding technique, which here is split into BaseList::Decode() and the static method Base::Decode().

答:
What I ended up when writing serialization was the following:

```<code>class ParserPairBase
{
public:
//virtual std::type_info TypeInfo() const=0;
virtual size_t SizeOf() const=0;
struct PtrSize
{
  char *ptr;
  size_t size;
};
virtual PtrSize BaseParse(std::string s, bool &success) const=0;
virtual std::string BaseCreate(PtrSize psz) const=0;
};

template<class T>
class ParserPair : public ParserPairBase
{
public:
   virtual std::string Create(T t) const=0;
   virtual T Parse(std::string s, bool &success) const=0;
   //std::type_info TypeInfo() const { return typeid(T); }
   virtual size_t SizeOf() const { return sizeof(T); }
   virtual PtrSize BaseParse(std::string s, bool &success) const
      {
      PtrSize sz;
      T *ptr = new T;
      sz.ptr = (char*)ptr;
      sz.size = sizeof(T);
      *ptr = Parse(s, success);
      return sz;
      }
    virtual std::string BaseCreate(PtrSize psz) const
       {
       T *ptr = (T*)psz.ptr;
       std::string s = Create(*ptr);
       return s;
       }
   };
</code>```

And then just derived classes will implement Create() and Parse():

```<code>class CharParser : public ParserPair<char>
{
public:
   std::string Create(char c) const { std::string s; s+=c; return s; }
   char Parse(std::string s, bool &success) const {
      if (s.length()!=1) { success = false; return ' '; }
      success = true;
      return s[0];
   }
};
</code>```

Unfortunately, this is getting too long for the site, but using these base classes, it's possible to create for example a parser for arbitrary structs. See this link for further details: http://sourceforge.net/p/gameapi/code/ci/master/tree/GameApi/Parser.hh

I'll create another answer for answering your actual question.

Body:
What I ended up when writing serialization was the following:

class ParserPairBase
{
public:
//virtual std::type_info TypeInfo() const=0;
virtual size_t SizeOf() const=0;
struct PtrSize
{
  char *ptr;
  size_t size;
};
virtual PtrSize BaseParse(std::string s, bool &success) const=0;
virtual std::string BaseCreate(PtrSize psz) const=0;
};

template<class T>
class ParserPair : public ParserPairBase
{
public:
   virtual std::string Create(T t) const=0;
   virtual T Parse(std::string s, bool &success) const=0;
   //std::type_info TypeInfo() const { return typeid(T); }
   virtual size_t SizeOf() const { return sizeof(T); }
   virtual PtrSize BaseParse(std::string s, bool &success) const
      {
      PtrSize sz;
      T *ptr = new T;
      sz.ptr = (char*)ptr;
      sz.size = sizeof(T);
      *ptr = Parse(s, success);
      return sz;
      }
    virtual std::string BaseCreate(PtrSize psz) const
       {
       T *ptr = (T*)psz.ptr;
       std::string s = Create(*ptr);
       return s;
       }
   };

And then just derived classes will implement Create() and Parse():

class CharParser : public ParserPair<char>
{
public:
   std::string Create(char c) const { std::string s; s+=c; return s; }
   char Parse(std::string s, bool &success) const {
      if (s.length()!=1) { success = false; return ' '; }
      success = true;
      return s[0];
   }
};

Unfortunately, this is getting too long for the site, but using these base classes, it's possible to create for example a parser for arbitrary structs. See this link for further details: http://sourceforge.net/p/gameapi/code/ci/master/tree/GameApi/Parser.hh

I'll create another answer for answering your actual question.


答:
How can I convince them that this is a bad idea?

It might not be a bad idea.

I've seen not a few systems where each event got its own tiny handler class, and the handlers were discovered and dependency injected at runtime leading to a fairly huge fragile mess.

Without knowing what you need to do, and what you might need to eventually do, it's hard to say for sure. But it probably is a bad idea.

On to your points, somewhat as a devil's advocate (since your programmer will likely have similar arguments if they want to put it all together).

The single file will become a merge nightmare, since adding any module will require adding logic to the central controller. If two engineers add two different features, one will have to resolve the conflicts in the central file.

Enh, this is probably overblown. The different conditions will be in their own blocks, limiting the conflict area. At least Visual Studio can automerge those sorts of conflicts well these days. I can't speak to other IDEs.

The central controller file will get excessively long, growing at least linearly with the number of modules, if not N2 with the with the number of interactions between different modules.

So what? Splitting the code into different classes will be at least that long, since you have the added overhead of all the class declaration ceremony. You're still doing the same work, so it's going to be the same length code (everything else being equal).

The central controller will be highly coupled—since it will have a dependency on every other module in the system—and have very little cohesion, with the blocks of logic only related because they're caused by any two modules interacting together.

So what? Even with a highly decoupled set of event handlers, something needs to know what they all are and how to tie them together - and that something is going to have just as many coupling points as the one big handler does. If anything, by explicitly stating the dependencies in one place, you can more easily see what they are and break them apart.

The dependencies between different modules will not be explicit, since a single controller will be responsible for handling those interactions.

Eh? In the normal decoupled version of this I've seen, an Inversion of Control container promptly obfuscates the concrete dependencies. I expect the interactions in the one big controller will be explicitly in code rather implicitly in convention or explicitly in some config file hidden away somewhere.

Writing unit tests for each module, or integration tests between two modules will be impossible without pulling in every other module via the central controller. The central controller itself will be pretty much untestable, outside of end-to-end testing.

Not always. If the big handler doesn't use all of the modules to handle the event you're testing, you don't need to mock all of the modules since they would be unused. It would take some care to do right, and it may be impossible given your requirements, but not a surefire argument.

Some other common arguments:

If someone changes one module, it causes our consumer to update all of them!

Depending on your requirements, they might need to do that anyways (because you version the entire system, because the dependencies are so pervasive that the change would cascade).

If it's in the big controller, we can't reuse/compose modules!

Sure, but almost every system I've seen like this couldn't do that anyways. The dependencies were too pervasive either between the modules or on cross cutting concerns (logging, security, data access, etc).

But the big thing to note is that all of my counter arguments are the sort of "it would be effectively equivalent" to the modular code. Why go through all the work of shuffling things around if it won't provide a clear benefit?

And largely, the complaints against the one big class are impacts of violating the Single Responsibility Principle. It is a well known guideline that has stood against criticism and the rigors of practical OO design for years. There is literally decades of evidence from programmers better than you, I or your coworker that says making a class with multiple responsibilities will lead to pain and badness.

Title: Why is modularity a good idea?

Body:
I have a programmer on my team who wants to take all the control flow logic for handling events sent by any module and put it all in a single file, because they think it will make an already-complex system easier to maintain and grow. How can I convince them that this is a bad idea?

Sources to reading material are welcome, as well as general arguments. Arguments for the idea are also welcome.*

Here's what I've got so far:

The single file will become a merge nightmare, since adding any module will require adding logic to the central controller. If two engineers add two different features, one will have to resolve the conflicts in the central file.

The central controller file will get excessively long, growing at least linearly with the number of modules, if not N2 with the with the number of interactions between different modules.

Any message handling logic that accesses internal state for a given module will either need to be wrapped in a function (this is not necessarily bad), or have its module expose that state (this is bad).

The central controller will be highly coupled—since it will have a dependency on every other module in the system—and have very little cohesion, with the blocks of logic only related because they're caused by any two modules interacting together.

The dependencies between different modules will not be explicit, since a single controller will be responsible for handling those interactions.

Writing unit tests for each module, or integration tests between two modules will be impossible without pulling in every other module via the central controller. The central controller itself will be pretty much untestable, outside of end-to-end testing.

* Implementing a state machine to control the flow of a system is not necessarily a bad idea, but different parts of the program still need to be modularized and not have to care about states or state transitions that don't matter to them.


问:
Algorithm to go from infix notation to a tree
I've been trying to figure out an algorithm to go from an infix equation to a syntax tree, like so:

(1+3)*4+5

```<code>      +
    *   5
  +   4
 1 3
</code>```

However, I don't just want it to handle operators, I want it to handle functions with arbitrary argument numbers as well, i.e:

max(1,3,7)*4+5

```<code>      +
    *   5
 max  4
1 3 7
</code>```

Here's the general algorithm I've come up with:

You start with the root node of the tree, containing a null value. You have a pointer which moves around the tree as you parse the expression, and starts pointed at the root node.

There are also some aspects of the tree I should probably clarify:

Inserting at a node means adding to the end of the node's children.

Injecting at a node means adding to a specific index in the node, and removing the node at that index and inserting it to the injected node. So, if node A has child B at index 0, and we inject node C at index 0, node A will have a child C which will have a child B.

Replacing at an index removes the node at that index and puts the alternate node in its stead. So if we have node A with child B at index 0, and we replace using C at index 0, we will have node A with child C.

Ok, so here's the algorithm so far.

For every token in the infix string:

if the token is a number

insert it as a child of the current node

if the token is an argument separator

traverse up the tree until the value of your current node is a function

if the token is a left parenthesis

if the value of the current node is not a function, insert our token as a child node, and set our current node to the token's node.

if the token is a right parenthesis

traverse until the current node is either a left parenthesis or a function

if the current node is a left parenthesis, replace it with its first child (index 0). This is equivalent to removing the parenthesis node from the tree structure, while keeping its first child intact.

traverse up one level, to the parent of the current node

if the token is a function

insert the token as a child node of the current node, and set the current node to the newly inserted child node

if the token is an operator

if the current node is not a left parenthesis or the root node

traverse up if

the current node is not at the root, or

the token is right associative and the precedence of the token is less than the precedence of the current node or

the token is left associative and the precedence of the token is less than or equal to the precedence of the current node

inject the token as a new node at the last index of the current node

set the current node to its newly added token child node

Once you have gone through all the tokens, return the first child of the root node.

Is there an existing algorithm I can check this against? Are there any obvious problems with this? Are there any particularly difficult to parse problems I can plug in using this and see if they work?

答:
Treat the comma as an infix operator.  Then

```<code>max(1,3,7)*4+5
</code>```

becomes

```<code>        +
       / \
      *   5
     / \
   max  4
    |
    ,
   / \
  ,   7
 / \
1   3
</code>```

The comma should have a lower precedence than your calculation operators (+ - * / etc.).

Body:
Treat the comma as an infix operator.  Then

max(1,3,7)*4+5

becomes

        +
       / \
      *   5
     / \
   max  4
    |
    ,
   / \
  ,   7
 / \
1   3

The comma should have a lower precedence than your calculation operators (+ - * / etc.).


答:
Ok, the actual question was about how to handle the difference between {FOO, 54} and {BAR, "hello"}. This is classic use case of an union:

```<code>struct A { int id; union { long val; std::string s; } un; };
</code>```

unfortunately, unions don't handle constructors very well, so std::string wont work very well inside union (unless they changed it recently :-). But there's another way to implement an union:

```<code>class Union {
public:
  Union() : m_s(0), m_val(0) {}
  Union(std::string s) : m_s(new string(s)), m_val(0) { }
  Union(long val) : m_s(0), m_val(new long(val)) { }
  ~Union() { delete m_s; delete m_val; }
  Union(const Union &u)
  : m_s(u.m_s ? new string(*u.m_s) : 0),
    m_val(u.m_val ? new long(*u.m_val) : 0) { }
  void operator=(const Union &u) {
        delete m_s; m_s=0;
        delete m_val; m_val=0;
        if (u.m_s) m_s = new std::string(*u.m_s);
        if (u.m_val) m_val = new long(*u.m_val);
        }
 private:
  std::string *m_s;
  long *m_val;
 };
</code>```

NULL pointers are indicating that the value is not being used. (note that this Union class becomes a nightmare to maintain, if you need to add more alternative types to it)

Now the required struct looks like this:

```<code>struct A { int id; Union u; };
</code>```

Once you have this, making an array out of it is very trivial:

```<code>std::vector<A> vec;
</code>```

will be able to store values like {{ID_FOO,33}, {ID_BAR,"hello"}}

Title: C++ design for encoder/decoder classes with different stored types

Body:
I need to handle different elements in a vector, each element owning a specific parameter (integer or string), so that I can easily handle encoding/decoding of a series of elements.

Encoding a list of elements serializes the elements, inserting a separator in-between each.

Decoding a string consists in finding the separators then for each substring, extracting the ID and type-specific value. Example (knowing that "FOO" is associated to an integer and "BAR" is associated to a string): "FOO=54,BAR=hello" gives {{ID_FOO, 54}, {ID_BAR, "hello"}} .

I have the current following bare design:

```<code>#include <cstdint>
#include <cstdlib>
#include <string>
#include <memory>

enum eID { /*...*/ };

// Base class
class Base {
private:
    enum eID m_Id;
public:
    Base(enum eID = 0): m_Id(eID) {}
    virtual std::string Encode() {
        // Return encoding of m_Id
    }
    static Base* Decode(const std::string &str) {
        Base *ptr;
        // Extract id
        // According to the kind of id, create a new Derived<T>
        // giving the substring to the constructor
        // ptr = new Derived<...>(id, str.substr(...));
        return ptr;
    }
};

template <class T>
class Derived<T> : public Base {
private:
    T m_Value;
public:
    Derived(enum eID id, const std::string &str); // participates to decoding
    std::string Encode();
};

template<>
Derived<std::string>::Derived(enum eID id, const std::string &str) {
    m_Value = str; // easy
}

template<>
std::string Derived<std::string>::Encode() {
    return static_cast<Base*>(this)->Encode() + m_Value;
}

template<>
Derived<long>::Derived(enum eID id, const std::string &str) {
    m_Value = strtol(str.c_str(), nullptr, 10);
}

template<>
std::string Derived<long>::Encode() {
    // Encode id and integer param to a string
}

class BaseList {
private:
    std::vector<std::unique_ptr<Base>> m_List;
public:
    void Append(Base *ptr) {
        m_List.push_back(std::unique_ptr<Base>(ptr));
    }
    std::string Encode() {
        // Call each Encode() function and concatenate strings together
        // Insert a delimiter in-between substrings
    }
    void Decode(const std::string &sToDecode) {
        // Look for delimiters in sToDecode
        // For each delimited substring:
        // - call Base::Decode() to allocate a new type-specific object
        // - push back into m_List
    }
}
</code>```

(This is not be a complete compiling example.)

Is it a logic design? How could it be optimized so that it may match any existing design pattern(s)? In particular I am concerned with the decoding technique, which here is split into BaseList::Decode() and the static method Base::Decode().

Body:
Ok, the actual question was about how to handle the difference between {FOO, 54} and {BAR, "hello"}. This is classic use case of an union:

struct A { int id; union { long val; std::string s; } un; };

unfortunately, unions don't handle constructors very well, so std::string wont work very well inside union (unless they changed it recently :-). But there's another way to implement an union:

class Union {
public:
  Union() : m_s(0), m_val(0) {}
  Union(std::string s) : m_s(new string(s)), m_val(0) { }
  Union(long val) : m_s(0), m_val(new long(val)) { }
  ~Union() { delete m_s; delete m_val; }
  Union(const Union &u)
  : m_s(u.m_s ? new string(*u.m_s) : 0),
    m_val(u.m_val ? new long(*u.m_val) : 0) { }
  void operator=(const Union &u) {
        delete m_s; m_s=0;
        delete m_val; m_val=0;
        if (u.m_s) m_s = new std::string(*u.m_s);
        if (u.m_val) m_val = new long(*u.m_val);
        }
 private:
  std::string *m_s;
  long *m_val;
 };

NULL pointers are indicating that the value is not being used. (note that this Union class becomes a nightmare to maintain, if you need to add more alternative types to it)

Now the required struct looks like this:

struct A { int id; Union u; };

Once you have this, making an array out of it is very trivial:

std::vector<A> vec;

will be able to store values like {{ID_FOO,33}, {ID_BAR,"hello"}}


问:
How to better isolate JOGL or LWJGL3 dependency from game clients?
I'm currently working on a project to develop a relatively small framework with the goal of supporting game development efforts for students in a course. The scope of this project is an OpenGL-based renderer and a 3D scene graph, and must be written in Java. (That's the course pre-req. for students.)

I'm familiar with OpenGL and shader-based programming. I've used JOGL and more recently LWJGL3. One important goal for me is to keep this library dependency hidden and student code ignorant of whatever decision I make here. However, I'm having difficulty in this effort.

While using JOGL and LWJGL3, I've noticed some key design decisions they've made that, in turn, seem to make it more difficult to keep the dependency from being 'leaked' to the client application.

The following is a list of some issues/trade-offs I've identified for both of them:

JOGL - Pros

Integrates with swing/awt/etc. package components (e.g. can use a JFrame for the OpenGL context and GLCanvas)

Allows client application to implement, register, and react to KeyListener, MouseListener, and other interfaces (i.e. students/clients can use the same event-driven input handling methods they've always used.)

Familiar 'environment' for students (e.g. using a GLCanvas is no different from using a Canvas, etc.)

JOGL - Cons

Required implementation of GLEventListener limits where I can make OpenGL calls (not difficult to hide this per se, but client must be able to work with shaders, which internally require OpenGL calls, which requires a valid gl instance)

Required GLAutoDrawable object for OpenGL calls is another constraint (obj cannot be cached)

Seems to force exposure of the GLAutoDrawable and related objects to client when its code needs to do something and we're not currently within the display(GLAutoDrawable) method override (e.g. client may want to do something like shaderProgram.setAttributeValue("attribName", 0.5f);, but instead has to do shaderProgram.setAttributeValue(gl, "attribName", 0.5f);)

LWJGL3 - Pros

No requirement for special objects (e.g. GLAutoDrawable) or interface restricting where/when OpenGL calls can be made.

Allows me flexibility in designing the client-visible APIs.

LWJGL3 - Cons

Uses GLFW, with its own Window management API & is incompatible with Java AWT components (e.g. cannot register KeyListener, MouseListener, etc.)

It's callback-based (i.e. must use glfwPollEvents(), GLFWKeyCallback, etc)

Seems to force exposure of the input-handling callbacks and related objects/functions to client (e.g. if client wants to exit, must  define/use GLFWKeyCallback, check GLFW_KEY_ESCAPE, glfwSetWindowShouldClose(...)

For example, to expand a bit more on the bold entries. The client may want to do something like shaderProgram.setAttributeValue("attribName", 0.5f);, but instead would be forced to do shaderProgram.setAttributeValue(gl, "attribName", 0.5f); after calling drawable.getGL() when using JOGL.

On the other hand, when using LWJGL3, if the client wants to handle inputs, it would be forced to do something similar to the code snippet below instead of just being able to react to a keyPressed event by implementing a KeyListener.

```<code>glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
    @Override
    public void invoke(long window, int key, int scancode, int action, int mods) {
        if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
            glfwSetWindowShouldClose(window, GL_TRUE);
        }
    }
});
</code>```

A few other things I've considered include the following:

(LWJGL3) Using the adapter design pattern to hide away the input management of LWJGL3, but this seems to be a significant amount of effort & complication (e.g. map each GLFW_KEY_* to some KeyEvent.VK_* constant) just for a start

(LWJGL3) The above would have to be provided as classes rather than interfaces b/c the callback objects would need to be contained (e.g. GLFWKeyCallback) to then deal with the behavior

(LWJGL3) A lot of complication/overhead just to handle inputs?...

(JOGL) Since the use of the GLAutoDrawable instance can/must not be cached (JOGL manages that internally and docs state your cached reference can become invalid, causing hard-to-track client crashes), perhaps in some way 'caching' calls made by client (e.g. shaderProgram.setAttributeValue(...) and then wait until code is running within display(...) override to apply requested changes, which would add complication and room for bugs that I'd rather live without, etc. (wouldn't even know where/how to start here)

Thought about libGDX, but that seems a lot more complicated than what I need, and still uses GLFW internally just like LWJGL3.

Things that I'd find helpful from you guys/gals out there:

Thoughts on how you'd deal with this situation

Concrete examples that clearly illustrates your point (i.e. code/pseudo-code is fine, just looking for more than "just do X"-type of responses)

The more detail you're able/willing to provide, the better-er :)

I'll update/clarify my original post as necessary if there're questions.

Thanks to everyone in advance.

答:
I am working on my own Java 3D engine with LWJGL which leads me to my answer below. I don't know much about JOGL.

Both LWJGL and JOGL are just Java bindings to accomplish the same thing, which is to call native code that changes the OpenGL state of the current context. For example, in the current thread, a call in LWJGL to glCreateProgram() will call the native version of glCreateProgram(), while a call in the JOGL version GL2ES2.glCreateProgram() (or whatever it may be) does the exact same thing. Knowing this, you may be able to combine the capabilities wanted from both frameworks.

As I know, a single thread in any application has only one OpenGL context associated with it, so ensure that anything that has to do with OpenGL is called within the same thread, and you should be fine to use both.

In your case, you can try using JOGL for the GUI aspect, and LWJGL for the raw OpenGL calls that you require.


问:
Best architecure approach to develop iOS app
I'm trying to create a calendar app similar to this design: Calendar Design

I'm currently using this calendar framework: CVCalendar and it's working great, but my question is, what do you think is the best approach to take for displaying the events beneath the calendar?

I see 2 options to take:

Option 1:
I use a UITableView and place the calendar view as the only TableViewCell in it's own section, and the events would be the rows underneath it in a seperate section.

The problem with that, is every time the user selects a new day, I need to load the events pertaining to that day which would require me to reload the whole TableView, including the calendar view which doesn't need to be reloaded.

Option 2:
I create custom views for the events, and add them as subviews in the scroll view along with the calendar view. That way, when the user clicks on a new day, I would just delete the event subviews and recreate them based off of the new data.

答:
How about option 3. Put the CVCalendarView on the VC's view, and a UITableView under the CVCalendarView. When the user taps a day, reload the table view with the new data. Since the calendar view is not in the table view, it will not need to be reloaded. When the user scrolls through the events of the day, the calendar will stay put.

That's how I would do it.

Option 4. If you really want the calendar to scroll off screen, then put the calendar view in the header view of the table view. Here too the table view can be reloaded without having to reload the calendar view.


答:
At some point you just need to graduate to a proper parser, because there are too many things to track and too many boundary cases.  Adding function calls to the peg.js example grammar, you get.

```<code>primary
  = integer
  / "(" additive:additive ")" { return additive; }
  / function_call

function_call
  = [a-z]+ "(" args ")"

args
  = (additive ("," additive)*)?
</code>```

Note this easily handles boundary cases like function calls and expressions nested within function calls:

```<code>max(3+4,min(6,(1+2)*3))+2
</code>```

Title: Algorithm to go from infix notation to a tree

Body:
I've been trying to figure out an algorithm to go from an infix equation to a syntax tree, like so:

(1+3)*4+5

```<code>      +
    *   5
  +   4
 1 3
</code>```

However, I don't just want it to handle operators, I want it to handle functions with arbitrary argument numbers as well, i.e:

max(1,3,7)*4+5

```<code>      +
    *   5
 max  4
1 3 7
</code>```

Here's the general algorithm I've come up with:

You start with the root node of the tree, containing a null value. You have a pointer which moves around the tree as you parse the expression, and starts pointed at the root node.

There are also some aspects of the tree I should probably clarify:

Inserting at a node means adding to the end of the node's children.

Injecting at a node means adding to a specific index in the node, and removing the node at that index and inserting it to the injected node. So, if node A has child B at index 0, and we inject node C at index 0, node A will have a child C which will have a child B.

Replacing at an index removes the node at that index and puts the alternate node in its stead. So if we have node A with child B at index 0, and we replace using C at index 0, we will have node A with child C.

Ok, so here's the algorithm so far.

For every token in the infix string:

if the token is a number

insert it as a child of the current node

if the token is an argument separator

traverse up the tree until the value of your current node is a function

if the token is a left parenthesis

if the value of the current node is not a function, insert our token as a child node, and set our current node to the token's node.

if the token is a right parenthesis

traverse until the current node is either a left parenthesis or a function

if the current node is a left parenthesis, replace it with its first child (index 0). This is equivalent to removing the parenthesis node from the tree structure, while keeping its first child intact.

traverse up one level, to the parent of the current node

if the token is a function

insert the token as a child node of the current node, and set the current node to the newly inserted child node

if the token is an operator

if the current node is not a left parenthesis or the root node

traverse up if

the current node is not at the root, or

the token is right associative and the precedence of the token is less than the precedence of the current node or

the token is left associative and the precedence of the token is less than or equal to the precedence of the current node

inject the token as a new node at the last index of the current node

set the current node to its newly added token child node

Once you have gone through all the tokens, return the first child of the root node.

Is there an existing algorithm I can check this against? Are there any obvious problems with this? Are there any particularly difficult to parse problems I can plug in using this and see if they work?

Body:
At some point you just need to graduate to a proper parser, because there are too many things to track and too many boundary cases.  Adding function calls to the peg.js example grammar, you get.

primary
  = integer
  / "(" additive:additive ")" { return additive; }
  / function_call

function_call
  = [a-z]+ "(" args ")"

args
  = (additive ("," additive)*)?

Note this easily handles boundary cases like function calls and expressions nested within function calls:

max(3+4,min(6,(1+2)*3))+2


问:
Does 'Iterable' interface look redundant in java?
By this below definition(pre 1.8) of Iterable,

```<code>package java.lang;

import java.util.Iterator;

public interface Iterable<T> {
    Iterator<T> iterator();
}
</code>```

I would say that, Iterable is dependent on Iterator interface as shown below,

```<code>package java.util;

public interface Iterator<E> {

    boolean hasNext();

    E next();

    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

}
</code>```

Standard recommendation is that, any implementation that implements Iterable interface becomes iterable.

But syntactically, MyClasscan implement interface Iterator and enable the implementation MyClass as iterable without explicitly mentioning  class MyClass **implements Iterable**{}, by adding Iterator<T> iterator(); behavior in Iterator interface instead of  Iterable interface. This would have simplified presenting only one interface(Iterator). Iterator can hold all the responsibilities that Iterable does.

So, What is the rational behind adding Iterator<T> iterator(); behavior in Iterable(redundant) interface instead of Iterator interface?

I am not clear with the purpose of introducing Iterable interface.

Please help me understand.

For me, this is not a duplicate question because this is an answer which talks about violation of SRP.

答:
Iterator is stateful, Iterable is stateless.

Iterator knows where it is at the moment, but Iterable shouldn't, because it can be iterated by two (or more) independent "actors".

Basically Iterable is able to provide anyone with a brand new Iterator on demand.

It looks like this question keeps on coming up, although mostly on StackOverflow not here:

https://stackoverflow.com/questions/6863182/what-is-the-difference-between-iterator-and-iterable-and-how-to-use-them

https://stackoverflow.com/questions/839178/why-is-javas-iterator-not-an-iterable


问:
How to encourage contributors to choose rebasing over merging?
Here's a chunk of commit messages from our repo. It's mercurial but I believe in this context git will be relevant as well:

```<code>Viktor Bubnidze TEST: chat send url fix changeset
Kate Gunicky    PROJ-15754: [work-space] Chat Section CSS issues
Vadym Malan     Merge
Vadym Malan     TEST: char send url test
Ron Cosby       Merge
Ron Cosby       Merge
Ron Cosby       Merge
Ron Cosby       Merge
Ron Cosby       PROJ-15711: Fix the jsdoc template
Anna  Flint     Merge
</code>```

See what's going on - each time user updates while goint to push and found that repo is outdated just merges. This creates informational noise and makes log reading less comfortable. Also, merges to my understanding are not completely cheap in terms of disk space.

My question is - what can be done to encourage contributors to use rebase whenever it is possible. For instance, it's relatively easy to introduce hooks that forbids merge commmits at all. In fact, there are already lot of restrictions in our project - like commit message naming etc. I'm not sure that being restrictive is the best thing to do in this particular case.

People are choosing merges because it is the cheapest strategy for syncing.
If some other strategy will work for them and be more pleasant - they'll just switch to it.

The thing is I can not come up with any elegant "kind" solution for this.
To be completely honest with you, the tempation to play as a dictator is quite strong. But I just want to learn somthing new. Something, well, more peaceful.

答:
One way of 'hiding' the merge change sets is to use Mercurial Queues. It is an extension currently being distributed along with Mercurial.

In short, they are mutable change sets, known as patches in a patch-queue. Instead of having to merge, your users can rebase and then apply the patch or patches they want to push on top of the tip of the rebase, finalise the patch(es) and push.

You still will have to educate your users to use the patch queue properly.

Maybe there is a different reason for your users to merge...

A distributed version control system like Mercurial implies merging, that is the whole idea of it. People can work disconnected and at a later stage merge their work into the main branch. Mercurial makes merging easy, so I'm not surprised that your users use it - it is the path of lest resistance.

Merging is also (almost) impossible to prevent. Say, all of your users have a commit hook installed that checks upstream before committing. Then your users have to rebase before they can commit and thus prevent merges. If two users rebase first and then commit at the same time (which is allowed by the commit hook) one of them will still have to merge.

To prevent this, a number of the teams at my current work-place use commit & push tokens. Only the person who owns the token, is allowed to commit and then push. This prevents merging (at least most of the time).

On one of my previous work-places, they used a gatekeeper. The central repository was always closed. Only when your code was reviewed and approved (this involved an official document that required signatures of multiple people), the gatekeeper allowed you to commit and push. This was a very elaborate process.

You see, there are several ways of preventing merging ;-)


答:
Ask for meaningful commit messages

The problem does not come from using merge commits instead of rebase in this particular case. It is  the lack of meaningful commit messages. For example, without seeing your repository, this could very well be a merge commit:

```<code> Ron Cosby       PROJ-15711: Fix the jsdoc template
</code>```

But contrary to the other commits, this one has a clear meaning.
Similarly, imagine you have:

```<code> Vadym Malan     Rebase
</code>```

This rebase commit is the same kind of noise as current merge commits (edit: assuming this was obtained by collapsing commits and changing the message, of course). Granted, the tool design is such that merge commits have automatic messages and rebase do not, but that is in no way an argument to force people to use rebase, because rebasing does not automatically prevent you from having noise in your history.

It is easier to commit merges without thinking about a message, because there is a default message for merges. For example, originally, git would not even fire the editor for merge messages, which was recognized as being a design error:

[...] my main issue
  is that git makes it way too easy to have bad merge messages.

(Linus Torvalds)

This has been fixed, but still, the default message should not be used. Note also that the default message in git at least indicates which branches are being merged, which could provide more informations than simply "Merge".

Also, merges to my understanding are not completely cheap in terms of disk space.

No, they are as cheap as regular commits, don't worry. To be more precise, even if they take more space, this is not important. You don't decide to rebase instead of doing a merge commit because it could save you a couple of bytes.

How is it relevant to your question?

You said:

People are choosing merges because it is the cheapest strategy for
  syncing. If some other strategy will work for them and be more
  pleasant - they'll just switch to it.

Imagine you tell your team:

"Team, from now on we want to have descriptive commit messages. Yes, Ron, that includes merge commits. You better follow this policy, or else* ..."

(* this part is optional)

Then, your merge-oriented people will:

see it as a burden and decide to rebase instead;

or, they are okay with the new policy and will write good commit messages.

You win in both cases.

Title: How to encourage contributors to choose rebasing over merging?

Body:
Here's a chunk of commit messages from our repo. It's mercurial but I believe in this context git will be relevant as well:

```<code>Viktor Bubnidze TEST: chat send url fix changeset
Kate Gunicky    PROJ-15754: [work-space] Chat Section CSS issues
Vadym Malan     Merge
Vadym Malan     TEST: char send url test
Ron Cosby       Merge
Ron Cosby       Merge
Ron Cosby       Merge
Ron Cosby       Merge
Ron Cosby       PROJ-15711: Fix the jsdoc template
Anna  Flint     Merge
</code>```

See what's going on - each time user updates while goint to push and found that repo is outdated just merges. This creates informational noise and makes log reading less comfortable. Also, merges to my understanding are not completely cheap in terms of disk space.

My question is - what can be done to encourage contributors to use rebase whenever it is possible. For instance, it's relatively easy to introduce hooks that forbids merge commmits at all. In fact, there are already lot of restrictions in our project - like commit message naming etc. I'm not sure that being restrictive is the best thing to do in this particular case.

People are choosing merges because it is the cheapest strategy for syncing.
If some other strategy will work for them and be more pleasant - they'll just switch to it.

The thing is I can not come up with any elegant "kind" solution for this.
To be completely honest with you, the tempation to play as a dictator is quite strong. But I just want to learn somthing new. Something, well, more peaceful.

Body:
Ask for meaningful commit messages

The problem does not come from using merge commits instead of rebase in this particular case. It is  the lack of meaningful commit messages. For example, without seeing your repository, this could very well be a merge commit:

 Ron Cosby       PROJ-15711: Fix the jsdoc template

But contrary to the other commits, this one has a clear meaning.
Similarly, imagine you have:

 Vadym Malan     Rebase

This rebase commit is the same kind of noise as current merge commits (edit: assuming this was obtained by collapsing commits and changing the message, of course). Granted, the tool design is such that merge commits have automatic messages and rebase do not, but that is in no way an argument to force people to use rebase, because rebasing does not automatically prevent you from having noise in your history.

It is easier to commit merges without thinking about a message, because there is a default message for merges. For example, originally, git would not even fire the editor for merge messages, which was recognized as being a design error:

[...] my main issue
  is that git makes it way too easy to have bad merge messages.

(Linus Torvalds)

This has been fixed, but still, the default message should not be used. Note also that the default message in git at least indicates which branches are being merged, which could provide more informations than simply "Merge".

Also, merges to my understanding are not completely cheap in terms of disk space.

No, they are as cheap as regular commits, don't worry. To be more precise, even if they take more space, this is not important. You don't decide to rebase instead of doing a merge commit because it could save you a couple of bytes.

How is it relevant to your question?

You said:

People are choosing merges because it is the cheapest strategy for
  syncing. If some other strategy will work for them and be more
  pleasant - they'll just switch to it.

Imagine you tell your team:

"Team, from now on we want to have descriptive commit messages. Yes, Ron, that includes merge commits. You better follow this policy, or else* ..."

(* this part is optional)

Then, your merge-oriented people will:

see it as a burden and decide to rebase instead;

or, they are okay with the new policy and will write good commit messages.

You win in both cases.


问:
Syncing graph of data to other database (like data)
Switching to new system and need to keep old data going for some time. So, we need to update old database with data when new system being updated.

It's a transactional data, like orders/shipments. Databases similar in principle but structures different. When change made to Order in new system - up to 10 tables need to be synced.

Here is my dilemma. How to go about transactions? Obviously, whole batch need to be wrapped into transaction. But it becomes pretty big chunk of code inside of transaction. I'm trying to minimize time "in transaction" and instead of just running "UPDATE" - I'm first checking (querying) destination if any of the fields was changed and then mark record for update. So, in the end, inside transaction we running updated on only records that only actually changed, not refreshing whole thing.

I'm just curious what you think about approach? We have much more code upfront (before transaction) but then actual transaction is super-light, instead of refreshing 20 rows in 10 tables - we only may refresh 1 table 1 row. Does this make sense?

答:
I think batch processing is what you are looking for.

You can separate a big transaction into smaller batches, in order to avoid sending huge packets in the database and make the locks have smaller duration.

The tools you should use depend on the technology you are using, but batch processing is very common and every language has a related API.

If you are using Java, you can check this link to see an example of using JDBC batch API.

If want to use a framework, Spring is a framework providing a lot of functionalities (Batch API included). You can check this link to see some usages.


问:
Is localStorage under The Cookie Law?
I'd like to avoid having the cookies banner on my websites where possible. Could I store session id's in localStorage to bypass implementing the banner?</p>

答:
If you don't use cookies at all then it would be a huge misinformation to warn your visitors about using cookies. It may even be useful to explicitly state that you don't use cookies. Remember that warnings about cookies are for people who want to avoid cookies so they should know when they finally get to a rare website that doesn't use them. But you may still need to warn about other things, like local storage. Just don't call it cookies if those are not cookies because it would be a misinformation that can even be against the law.

According to The EU Cookie Law website:

Is is just cookies?

No - The law also affects anything that acts like a cookie, for
  example:

Flash Cookies

HTML5 Local Storage

The ICO has said that it isn't good
  enough to just re-implement the tracking some other way outside of
  cookie storage.

According to The Cookie Collective:

There are other technologies, like Flash and HTML5 Local Storage that
  do similar things, and these are also covered by the legislation, but
  as cookies are the most common technology in use, it has become known
  as the Cookie Law.

See also:

Localstorage vs. Cookies vs. The law by Johan van Tongeren

Title: Is localStorage under The Cookie Law?


问:
private method that uses no instance members - better static?
I have a private helper method that uses no instance variables or methods, I feel it would be less confusing if it was static (this way, it's given fewer points it can access).

I am a bit unsure if this question applies to private methods too.

I've also taken a look at this second question but again testing is not going to test private static helper methods directly.

Question: Why shouldn't I make my private helper methods static? Is it the confusion that would maybe lead someone to reuse it in a static context? As far as I see, that should be fine.

Any thoughts and suggestions are appreciated.

答:
The widespread antipathy towards static methods is largely due to fear that you won't be able to override a method easily for testing the class or mocking to test another class.

With a private method this isn't a concern, so my opinion is: if it can be static, make it static - this acts as a useful bit of automatic documentation ("this method does not depend on any instance state at all"). You shouldn't rewrite helper methods so that the become static-capable (e.g. by replacing field access with input parameters), but if this is its natural form then there's no harm and a little bit of gain.


答:
To answer this, we should clarify the definition of static:

Static methods are meant to be relevant to all the instances of a class rather than to any specific instance. They are similar to static variables in that sense. An example would be a static method to sum the values of all the variables of an instance for a class. For example, if there were a Product class it might have a static method to compute the average price of all products.

Any static method can become a non-static method, so being static makes a statement about the impact calling such a method would have on your instance, which is to say none unless of course you were passing said instance to the static method (thus defeating the purpose of being static).

This method holds no state to do its job properly and could refer to any instance, so I would say yes, you should make it static.  However do be sure to leave it also private, since it is a method that only makes sense in the context of your class, and until that changes, it should remain private.

If you find yourself with several such private static helper methods, you should consider creating a final class with private constructor containing only protected static methods, which can only be called by classes in your package.

I hope that answers your question.

Title: private method that uses no instance members - better static?

Body:
I have a private helper method that uses no instance variables or methods, I feel it would be less confusing if it was static (this way, it's given fewer points it can access).

I am a bit unsure if this question applies to private methods too.

I've also taken a look at this second question but again testing is not going to test private static helper methods directly.

Question: Why shouldn't I make my private helper methods static? Is it the confusion that would maybe lead someone to reuse it in a static context? As far as I see, that should be fine.

Any thoughts and suggestions are appreciated.


问:
What is the motivation for casting a pointer into a integer?
I'm doing some changes in the Linux kernel code and have noticed a pointer being cast into integer.

Check out buf below (full code):

```<code>snd_pcm_sframes_t snd_pcm_lib_read(struct snd_pcm_substream *substream, void __user *buf, snd_pcm_uframes_t size)
{
    ....
    return snd_pcm_lib_read1(substream, (unsigned long)buf, size, nonblock, snd_pcm_lib_read_transfer);
}
</code>```

It gets covered from void __user *buf to (unsigned long)buf. Afterwards in the code buf is treated as a long and not as a pointer.

Even though on the technical levels they are both numbers in memory, so far  I've perceived conceptually as different things. Is there a low level pattern on when this is used?

答:
A typical use case (in hosted user-code applications) to cast some pointer to an intptr_t (from <stdint.h> standard C99 or C11 header) is to compute some hash code on that pointer:

```<code>uint32_t hash_of_foo_ptr(struct foo_st *foo) {
   return (uint32_t)(((intptr_t)foo) * 613) ^ ((intptr_t)foo % 51043));
}
</code>```

For historical reasons (i.e. Linux came before C99), the Linux kernel uses unsigned long instead of uintptr_t (the unsigned integral type of the same sizeof as pointers) or intptr_t

Also, user-space to kernel-space transmissions (e.g. arguments of syscalls) is in the Linux kernel in terms of long or unsigned long (again, you'll better think in term of intptr_t or uintptr_t). Even when you transmit addresses from user-space to kernel-space, you need to think about address spaces and virtual memory (and it is becoming complex, since user-space and kernel-code live in different address spaces).

A quote on the topic from LDD3:

Although, conceptually, addresses are pointers, memory administration
  is often better accomplished by using an unsigned integer type; the
  kernel treats physical memory like a huge array, and a memory address
  is just an indexinto the array. Furthermore, a pointer is easily
  dereferenced; when dealing directly with memory addresses, you
  almost never want to dereference them in this manner. Using an integer
  type prevents this dereferencing, thus avoiding bugs. Therefore,
  generic memory addresses in the kernel are usually unsigned long ,
  exploiting the fact that pointers and long integers are always the
  same size, at least on all the platforms currently supported by Linux.

Note that the Linux kernel is not coded in hosted academically standard portable C99. It is a freestanding program, coded with a few particular C compilers in mind (GCC and perhaps also in the future Clang/LLVM...).

The Linux kernel is using some GCC extensions to C (e.g. __attribute__-s, builtins, computed goto-s, etc...), perhaps wrapped with macros. Most of these extensions are also supported by Clang / LLVM.

Kernel newbies & lkml are probably good places to ask about that.

Body:
A typical use case (in hosted user-code applications) to cast some pointer to an intptr_t (from <stdint.h> standard C99 or C11 header) is to compute some hash code on that pointer:

uint32_t hash_of_foo_ptr(struct foo_st *foo) {
   return (uint32_t)(((intptr_t)foo) * 613) ^ ((intptr_t)foo % 51043));
}

For historical reasons (i.e. Linux came before C99), the Linux kernel uses unsigned long instead of uintptr_t (the unsigned integral type of the same sizeof as pointers) or intptr_t

Also, user-space to kernel-space transmissions (e.g. arguments of syscalls) is in the Linux kernel in terms of long or unsigned long (again, you'll better think in term of intptr_t or uintptr_t). Even when you transmit addresses from user-space to kernel-space, you need to think about address spaces and virtual memory (and it is becoming complex, since user-space and kernel-code live in different address spaces).

A quote on the topic from LDD3:

Although, conceptually, addresses are pointers, memory administration
  is often better accomplished by using an unsigned integer type; the
  kernel treats physical memory like a huge array, and a memory address
  is just an indexinto the array. Furthermore, a pointer is easily
  dereferenced; when dealing directly with memory addresses, you
  almost never want to dereference them in this manner. Using an integer
  type prevents this dereferencing, thus avoiding bugs. Therefore,
  generic memory addresses in the kernel are usually unsigned long ,
  exploiting the fact that pointers and long integers are always the
  same size, at least on all the platforms currently supported by Linux.

Note that the Linux kernel is not coded in hosted academically standard portable C99. It is a freestanding program, coded with a few particular C compilers in mind (GCC and perhaps also in the future Clang/LLVM...).

The Linux kernel is using some GCC extensions to C (e.g. __attribute__-s, builtins, computed goto-s, etc...), perhaps wrapped with macros. Most of these extensions are also supported by Clang / LLVM.

Kernel newbies & lkml are probably good places to ask about that.

ContentLicense: CC BY-SA 4.0


问:
C++ Iterators: Best practice to represent end of range - Last or Beyond-last?
I am writing a library which deals a lot with sub-sequences of ordered containers.

So for example I have a container (1,2,3,4,5,6) and a user wants to access (3,4,5).

I am providing the subsequence by a pair of iterators, pointing to its first and last element respectively, i.e. 3 and 5.

Since the library is written in C++ and AFAIK the std convention is to have the last iterator point beyond the last element, I am wondering if what I am doing is good practice or wether I should return a pair of iterators, pointing to the first and beyond last element respectively, i.e. 3 and 6?

Also from a programming perspective, it complicates things when using std functionality, for example to count the number of elements, I have to do:

```<code>int elementCnt = std::distance(startIt, endIt) + 1;
</code>```

答:
You wrote:

The std convention is to have the last iterator point beyond the last element

I think I can help your mental model by giving you two little replies
(one section each).

Don't think of it as beyond-last indexing, think of it as edge-based indexing

Why edge-based indexing (right-open interval indexing) is nice

Don't think of it as beyond-last indexing, think of it as edge-based indexing

I've substantially simplified and C++ified this section thanks to a very helpful comment by
Snowman:

C++ iterators are defined in terms of "which item will it retrieve next" instead of "to which item is it currently pointing?

So, it helps me to think of an iterators as resting not on an item, but on the edge just before it.

For sub-sequences with a start and a stop, instead of numbering the
items, I mentally number the edges between the items. 0 is the edge
before the first item. The startIt is the edge I start at; the
stopIt is the edge I stop at.

The following picture is adapted from An informal introduction to Python.

```<code>   item    0   1   2   3   4   5
         +---+---+---+---+---+---+
         | P | y | t | h | o | n |
         +---+---+---+---+---+---+
iterator 0   1   2   3   4   5   6
</code>```

So startIt = 2 and stopIt = 5 leads to t, h, o.

Why edge-based indexing (right-open interval indexing) is nice

You get some really nice properties:

number of items in a subsequence: n = stop - start

To create neighbouring subsequences, stop of one == start of the next.

Examples below. I'm using Python syntax below because I don't know C++.
If somebody is willing to translate this section into C++ (Don't bother
leaving the Python), I will be very grateful. Anyway, the notation is
not important: just read [start:stop] as startIt and stopIt.

This is the container we'll be using

```<code>my_container = [ 'a', 'b', 'c', 'd' ]
## edges       ^    ^    ^    ^     ^
##             0    1    2    3     4
</code>```

Access sub-sequences by slicing like c[start:stop] -- you get
everything between edges 1 and 3.

```<code>my_container[1:3] == ['b', 'c']
</code>```

To get a slice of length 3, I make sure stop = start + 3

```<code>my_container[1:4] == ['b', 'c', 'd']
# or do stop - start to find out how long the slice is:
4 - 1 == 3  # 3 elements in this slice.
</code>```

I want one slice to start where the previous slice ends. So, I let the first
slice end on edge x, and the second one start on edge x. This way I
cleanly split the container in two.

```<code>my_container[0:3] == ['a', 'b', 'c']
my_container[3:4] == ['d']
</code>```

Closing remark

Do read the essay by Edsger W. Dijkstra in
manlio's answer.
It's less than 700 words, with crystal-clear thinking and equally-clear
handwriting (and a link to a html version inside).

Body:
You wrote:

The std convention is to have the last iterator point beyond the last element

I think I can help your mental model by giving you two little replies
(one section each).

Don't think of it as beyond-last indexing, think of it as edge-based indexing

Why edge-based indexing (right-open interval indexing) is nice

Don't think of it as beyond-last indexing, think of it as edge-based indexing

I've substantially simplified and C++ified this section thanks to a very helpful comment by
Snowman:

C++ iterators are defined in terms of "which item will it retrieve next" instead of "to which item is it currently pointing?

So, it helps me to think of an iterators as resting not on an item, but on the edge just before it.

For sub-sequences with a start and a stop, instead of numbering the
items, I mentally number the edges between the items. 0 is the edge
before the first item. The startIt is the edge I start at; the
stopIt is the edge I stop at.

The following picture is adapted from An informal introduction to Python.

   item    0   1   2   3   4   5
         +---+---+---+---+---+---+
         | P | y | t | h | o | n |
         +---+---+---+---+---+---+
iterator 0   1   2   3   4   5   6

So startIt = 2 and stopIt = 5 leads to t, h, o.

Why edge-based indexing (right-open interval indexing) is nice

You get some really nice properties:

number of items in a subsequence: n = stop - start

To create neighbouring subsequences, stop of one == start of the next.

Examples below. I'm using Python syntax below because I don't know C++.
If somebody is willing to translate this section into C++ (Don't bother
leaving the Python), I will be very grateful. Anyway, the notation is
not important: just read [start:stop] as startIt and stopIt.

This is the container we'll be using

my_container = [ 'a', 'b', 'c', 'd' ]
## edges       ^    ^    ^    ^     ^
##             0    1    2    3     4

Access sub-sequences by slicing like c[start:stop] -- you get
everything between edges 1 and 3.

my_container[1:3] == ['b', 'c']

To get a slice of length 3, I make sure stop = start + 3

my_container[1:4] == ['b', 'c', 'd']
# or do stop - start to find out how long the slice is:
4 - 1 == 3  # 3 elements in this slice.

I want one slice to start where the previous slice ends. So, I let the first
slice end on edge x, and the second one start on edge x. This way I
cleanly split the container in two.

my_container[0:3] == ['a', 'b', 'c']
my_container[3:4] == ['d']

Closing remark

Do read the essay by Edsger W. Dijkstra in
manlio's answer.
It's less than 700 words, with crystal-clear thinking and equally-clear
handwriting (and a link to a html version inside).


问:
Help me design this use case
I have following entities:

Data:

User_id

Categories: Interests, Disinterests, Categories A, B C...

Each categories have sub categories: Interests=Gaming, Physics, Programming etc..

Now each user could belong to multiple sub categories.

So there is M:N relation ship between categories and users.

Scale:

1 Billion Users

100 Categories each could have subcategories ranging form 100 - 10,000

Operations Needed

Batch Read and Write: Selection and Projection given user_id. E.g. Get all the Interests of user A.

Real Time Read and Write: I need to get all the users for a given field like Interest:Games.

Current Design

I used separate files for each sub categories containing list of users. Redis server has keys-value pairs like

```<code><userId_InterestId:games,programming>
</code>```

However this design has many limitations, like slow access times due to disk operations to get all users for a given category. Huge number of keys in Redis i.e. number of (users * number of sub_categories).

I need a change of design

Current plan is to use MongoDb to maintain hierarchical data for  user <-> categories mapping.

```<code><User_id, Interests, A, B, C>.
</code>```

Each categories will have children fields. Since MongoDB is in-memory DB access using user_id should be faster right? But how about reverse query where I specify Interest::Programming as key? Is there any better way I could design it?

答:
Here's what I would do:  make no distinction between categories and subcategories.  Each category would have parent category associated with it, which may be null (category and not subcategory).

If I understand correctly, categories are not children of users, so if a user gets deleted, it won't delete its categories.  In that case, you will need a child table of user called UserCategories that associate a user id with a particular category.

So now, if you want to find all categories of a user, you have a child table which gives you this information.  Inversely if you have a category, you can find all users associated with its id given UserCategories.  By eliminating the need for subcategories to pass through a category, you've directly linked Users with subcategories and thus it becomes much easier to manage.

Obviously in your program, you may handle a category with a parent as a "subcategory" and treat it differently, but in the database, it only means a category with a parent category.

Title: Help me design this use case


问:
In MVC, what is the difference between controller and router?
Do they mean the same thing (attaching URLs to actions, or actions to URLs) or is there any difference I'm missing?

Example: http://github.com/dannyvankooten/PHP-Router vs. http://konstrukt.dk

答:
Routers are part of the controller layer. The router processing mechanism is a replacement of the old school Front Controller pattern (the big switch in the entry point).

In a modern framework a router defines a direct connection between a "kind" of possible requests and its processor. By contrast, a controller gets just identifying information, and parses this data in its own context.


答:
MongoDB would allow you to create an index on Interests. When you create an index for a field which includes arrays, each array entry gets a separate index entry. So when your documents look like this:

```<code>{
    _id:<<Objectid>>
    interests: [
        "Programming",
        "Knitting",
        "Paragliding"
    ]
}
</code>```

a query like db.collection.find({interests:"Programming"}) would give you all documents where the interests array has an entry "Programming" and would benefit from an index on interests.

Title: Help me design this use case

Body:
I have following entities:

Data:

User_id

Categories: Interests, Disinterests, Categories A, B C...

Each categories have sub categories: Interests=Gaming, Physics, Programming etc..

Now each user could belong to multiple sub categories.

So there is M:N relation ship between categories and users.

Scale:

1 Billion Users

100 Categories each could have subcategories ranging form 100 - 10,000

Operations Needed

Batch Read and Write: Selection and Projection given user_id. E.g. Get all the Interests of user A.

Real Time Read and Write: I need to get all the users for a given field like Interest:Games.

Current Design

I used separate files for each sub categories containing list of users. Redis server has keys-value pairs like

```<code><userId_InterestId:games,programming>
</code>```

However this design has many limitations, like slow access times due to disk operations to get all users for a given category. Huge number of keys in Redis i.e. number of (users * number of sub_categories).

I need a change of design

Current plan is to use MongoDb to maintain hierarchical data for  user <-> categories mapping.

```<code><User_id, Interests, A, B, C>.
</code>```

Each categories will have children fields. Since MongoDB is in-memory DB access using user_id should be faster right? But how about reverse query where I specify Interest::Programming as key? Is there any better way I could design it?

Body:
MongoDB would allow you to create an index on Interests. When you create an index for a field which includes arrays, each array entry gets a separate index entry. So when your documents look like this:

{
    _id:<<Objectid>>
    interests: [
        "Programming",
        "Knitting",
        "Paragliding"
    ]
}

a query like db.collection.find({interests:"Programming"}) would give you all documents where the interests array has an entry "Programming" and would benefit from an index on interests.


问:
How often should RAII be used?
I've been attempting to learn C++, but it is famously plagued by bad tutorials. I learned about a clever little trick called RAII (Resource Acquisition is Initialization), where one wraps a heap variable in an object placed on the stack. One would free the resources in the destructor of this object, so one would not have to worry about calling delete on the heap based object. However, I also know that you are supposed to create as few objects as possible, as to save RAM. Which brings me to my question, how much should I use RAII? Especially in a project that creates a lot of heap variables.</p>

答:
How often should RAII be used?

As often as it makes sense to use (that is, whenever you have an operation that will need to be inverted/undone/closed/finalized/committed/etc. you should probably use RAII).

However, I also know that you are supposed to create as few objects as possible, as to save RAM.

No; This is a form of premature optimization which is bad enough, but it also relies on a fallacy:

The number of variables in the code should not be a limiting factor in using RAII, because if you need a variable allocated, the allocation will be the same, whether it is in a wrapper or raw. An extra RAII wrapper will not add anything significant to the memory footprint of the application.

In other words, the following pieces of code should have the same (or comparable) memory footprints:

```<code>resource* allocate_resource() { return new resource{}; }
void release_resouce( resource * r ) { delete resource; }

// client code
auto r = allocate_resource();
release_resouce(r);
</code>```

and

```<code>struct resource_ptr {
    resource * r_;
    resource_ptr() : r_ { new resource }{}
    ~resource_ptr() { delete r_; }
};

// client code:
resource_ptr p;
</code>```

Both the resource* in the first sample and the resource_ptr instance in the second will have the same size (4 bytes on 32bit systems) and the calls to new/delete are in separate functions (which again, should have the same footprint whether in a structure or at top-level).

Something to keep in mind:

RAII can also be translated to mean "Responsibility acquisition is initialization", in which case, it will mean something more abstract (and larger) than "pointer/resource release in destructors". It effectively applies to any operation that requires a counter-operation later:

files that are opened will need to be closed

database transactions will need to be committed or rolled back

mutexes that are locked will need to be unlocked

network connections that have been opened will need to be closed

None of these are heap variables, but RAII applies naturally to all of them.

Title: How often should RAII be used?

Body:
How often should RAII be used?

As often as it makes sense to use (that is, whenever you have an operation that will need to be inverted/undone/closed/finalized/committed/etc. you should probably use RAII).

However, I also know that you are supposed to create as few objects as possible, as to save RAM.

No; This is a form of premature optimization which is bad enough, but it also relies on a fallacy:

The number of variables in the code should not be a limiting factor in using RAII, because if you need a variable allocated, the allocation will be the same, whether it is in a wrapper or raw. An extra RAII wrapper will not add anything significant to the memory footprint of the application.

In other words, the following pieces of code should have the same (or comparable) memory footprints:

resource* allocate_resource() { return new resource{}; }
void release_resouce( resource * r ) { delete resource; }

// client code
auto r = allocate_resource();
release_resouce(r);

and

struct resource_ptr {
    resource * r_;
    resource_ptr() : r_ { new resource }{}
    ~resource_ptr() { delete r_; }
};

// client code:
resource_ptr p;

Both the resource* in the first sample and the resource_ptr instance in the second will have the same size (4 bytes on 32bit systems) and the calls to new/delete are in separate functions (which again, should have the same footprint whether in a structure or at top-level).

Something to keep in mind:

RAII can also be translated to mean "Responsibility acquisition is initialization", in which case, it will mean something more abstract (and larger) than "pointer/resource release in destructors". It effectively applies to any operation that requires a counter-operation later:

files that are opened will need to be closed

database transactions will need to be committed or rolled back

mutexes that are locked will need to be unlocked

network connections that have been opened will need to be closed

None of these are heap variables, but RAII applies naturally to all of them.


问:
Depend in the direction of stability: How do I know what is more stable?
According to the Stable Dependencies Principle, the dependency

should be in the direction of the stability

But:

if you don't know what types of changes are likely, it is best to wait and see what happens as the system evolves.

Now:

Say I'm designing a blog, I am tempted to think the stability ranking is:

Comment - less likely to change

Post

User - more likely to change (because it's bigger?)

If I let Comment depend on Post, then Comment will change more likely. But also vice-versa, if I let Post depend on Comment, Post will change more likely, correct?

This wants to be a general argument, every app has a hierarchy similar to users, a main object and children.

Where is my best bet for change? higher level classes or lower level? And why?

答:
It's not about what is most likely to change, it's the difficulty of changing it.

The document you linked actually explains it quite well:

"Stable" roughly means "hard to change", whereas "instable" means
  "easy to change".

The concept can be better thought of as layers of software, it might be easy to change a UI, but much more difficult to change the API it calls, and even more difficult to change the DB that it is built upon. The DB is the stable part there.

For other systems, it might be really difficult to change the UI (e.g. a desktop app rolled out to 10,000 remote users) in which case it becomes the most stable.


问:
Is it necessary to discuss database changes
I am working on a project with a team of 4-5 people. Is it necessary to discuss the database changes with the team before implementing?  I am working on the database api's.

Is it better to discuss this or not? In my team are senior people. So can't I make changes myself and implement the change and explain the changes.

答: Table structure reflects relations between your object. Such changes are quite important and should be discussed.</p>

ContentLicense: CC BY-SA 2.5


问:
i++ vs i+=1 in cycles, why evaluate?
Why do most programmers use i++ in cycles? Doesn't it mean evaluate and increment. I find more logical to use just an increment i+=1, because that's all I want.

WriteLn(i++); would evaluate i and then increment, does it somehow remove the evaluation part if i++ is used in cycles?

答:
i++ means "fetch the value of i, then increment it, and return the value fetched". It can be used in expressions to both get a value and increase it in one go. It can also be used as a statement:

```<code>i++;
</code>```

in which case the value returned is discarded. In that case it's equivalent to i += 1;

When used in a loop, the same principle is being a applied:

```<code>for (var i = 0; i < 10; i++)
</code>```

is equivalent to writing:

```<code>for (var i = 0; i < 10; i += 1)
</code>```

The former is shorter (and arguably easier to read), so has become the norm.

There is a caveat though in saying that they are equivalent. Consider the following code:

```<code>var i = 0;
Console.WriteLine(i++);
Console.WriteLine(i += 1);
Console.WriteLine(++i);
</code>```

The output is 0, 2 and 3 as the former reads then increments, whereas the other two increment then read.

Title: i++ vs i+=1 in cycles, why evaluate?

Body:
i++ means "fetch the value of i, then increment it, and return the value fetched". It can be used in expressions to both get a value and increase it in one go. It can also be used as a statement:

i++;

in which case the value returned is discarded. In that case it's equivalent to i += 1;

When used in a loop, the same principle is being a applied:

for (var i = 0; i < 10; i++)

is equivalent to writing:

for (var i = 0; i < 10; i += 1)

The former is shorter (and arguably easier to read), so has become the norm.

There is a caveat though in saying that they are equivalent. Consider the following code:

var i = 0;
Console.WriteLine(i++);
Console.WriteLine(i += 1);
Console.WriteLine(++i);

The output is 0, 2 and 3 as the former reads then increments, whereas the other two increment then read.


答: There's no subtle technical reason for it. Using ++ is the more idiomatic form, probably because it saves one keystroke (or three if you put spaces around +=). The "evaluation part" will probably get optimized out in any langauge if it matters.</p>

Title: i++ vs i+=1 in cycles, why evaluate?

Body:
Why do most programmers use i++ in cycles? Doesn't it mean evaluate and increment. I find more logical to use just an increment i+=1, because that's all I want.

WriteLn(i++); would evaluate i and then increment, does it somehow remove the evaluation part if i++ is used in cycles?


问:
How/should I introduce a new pattern into my codebase
I have recently discovered the Builder pattern and the Step Builder pattern which are essentially just like object initialisers but with the Step Builder pattern you can add mandatory fields.

We have classes which have lots of constructors which have tons of parameters and each constructor is just a variation on what parameters are used so there is a lot of duplication and difficulty finding out which constructor is the right one to use. This gives us flexibility in creating our immutable object from lots of different places so I am not wanting to lose that. I believe that the step builder helps this because you can mandate particular fields and allow the flexibility that an object initializer gives.

However the team I am working in are not familiar with the builder pattern and cannot see its benefits. I don't really want to continue refectoring the code base just to be told its too complicated (because they can't see instantly how to us it) and I have to remove it, meaning that I have to spend another week or so working on it.

So my question is: How do you introduce a new pattern into an existing project while working in a team? Or even should I?

I know there are questions out there asking about how to introduce a new pattern in code but I specifically want to know how it affects a team and what I need to do to gain their buy in.

It might be worth noting that I am not a senior developer, if anything I am close to being a junior developer in terms of experience to the rest of my team.

答:
If you are getting major push back from the rest of your team, you should probably stop writing/refactoring things into that pattern, and use/leave the prevailing style instead, at least until you can find a persuasive argument in favor.

In your issue tracking system, do you have a body of fixed bugs where the problem was in the area of confusion over multiple constructors? If there is, you can point to that. If there isn't, then there may well be no problem with the status-quo.

Learning to pick your battles is important in teamwork.


问:
Getters with data conversion in Java VOs
I am working on a standard Spring application where DAO layer returns entities to service layer and service layer returns VOs to other services and controllers.

In a certain scenario, we have a VO that looks like this:

```<code>public class MyContainerVO{
    private Integer containerId;
    private String containerName;
    private List<ContainerChild> childList;

    //usual setters and setters

    public Map<String,String> getChildMap(){
        //creates a K,V map from the child list
        //with the key being child.getName() and value being child.getId()
    }
}
</code>```

I am confused whether this method getChildMap() should be in MyContainerVO or should it be moved to a utility class. I know that there should not be any business logic in the VO, but in my opinion the getChildMap() method only returns the data contained in MyContainerVO in a different format and thus does not qualify as business logic.

I could not find any answers in SO or programmers that deals with such scenario; most are about business logic in VOs that hit other classes creating close coupling which is a bad practice.

Kindly suggest what is the best approach in this scenario, or please point out some link that explains this in detail.

答:
Since the childList field is private, a method must be in MyContainerVO somewhere.

However, if the functionality to convert a Collection of ContainerChilds into a Map, based on various keys, is a useful general purpose utility, I would make it a static method of ContainerChild.  e.g.

```<code>public static Map<String,String> nameIdMap(Collection<ContainerChild> c);
public static Map<String,String> nameFooMap(Collection<ContainerChild> c);
</code>```

Since this utility is a method of ContainerChild, it knows about the fields of ContainerChild.  Obviously, if this function list became extremely large, you might pass the keys as parameters, use new fangled Java 8 closures, some pattern, etc...

Then, your actual code in MyContainerVO delegates all the logic to the utility.

```<code> public Map<String,String> getChildMap(){
   return ContainerChild.nameIdMap(this.childList);
 }
</code>```

Body:
Since the childList field is private, a method must be in MyContainerVO somewhere.

However, if the functionality to convert a Collection of ContainerChilds into a Map, based on various keys, is a useful general purpose utility, I would make it a static method of ContainerChild.  e.g.

public static Map<String,String> nameIdMap(Collection<ContainerChild> c);
public static Map<String,String> nameFooMap(Collection<ContainerChild> c);

Since this utility is a method of ContainerChild, it knows about the fields of ContainerChild.  Obviously, if this function list became extremely large, you might pass the keys as parameters, use new fangled Java 8 closures, some pattern, etc...

Then, your actual code in MyContainerVO delegates all the logic to the utility.

 public Map<String,String> getChildMap(){
   return ContainerChild.nameIdMap(this.childList);
 }