问:
Refactoring a god Manager class
I am running in the exact problem Robert Martin mentioned when having a class named Manager, mine has too much (redudant) code.

I am writing a system doing computations on many buffers containing data form a timestamped source.

The Buffers store different data types, they are template classes.

When a new Observation arrives, a BufferManager distributes and processes fields of the Observation to the different Buffers.

A common user operation is to access a time interval of a given buffer.

I have a BufferID emum of names in the BufferManager, one for each Buffer and then I have dictionaries (std::map) in the BufferManager, one for each type of Buffer.

The user then gets a desired interval of a Buffer by calling:

```<code>Type1Interval int1 =  BufferManager.getType1BufferInterval(BufferID, starTime, endTime)
...
TypeNInterval intN = BufferManager.getTypeNBufferInterval(BufferID, starTime, endTime)
</code>```

where the only difference between two such functions is that  getTypeJBufferInterval accesses the dictionary containing buffers of type J.

How can I, given a BufferID and a time interval, return the corresponding Buffer(values) without having to have all these different functions?

答:
You can use the single responsibility rule to split apart this manager class.

From your description, the BufferManager holds the collection of buffers,  distributes and processes the observations, and provides access to the intervals of the buffers.

The first step is to split the data from the manager. The map and the enum don't belong to the manager. Maybe you want to tie them together, in which case you'd make a separate class that owns the map and enum and say call it BufferMap.

Then you can have 2 different classes (or 3 if distributing and processing are separable). So make an ObservationProcessor, and a BufferIntervalCalculator.
Then your 2 methods become:

```<code>BufferIntervalCalculator bufferIntervalCalculator(bufferMap);
ObservationProcessor observationProcessor(bufferMap);
observationProcessor.Process(observation);

Type1Interval int1 = bufferIntervalCalculator.calculateInterval<Type1Interval>(BufferId, startTime, endTime);
...
TypeNInterval intN = bufferIntervalCalculator.calculateInterval<TypeNInterval>(BufferId, startTime, endTime);
</code>```

Title: Refactoring a god Manager class

Body:
You can use the single responsibility rule to split apart this manager class.

From your description, the BufferManager holds the collection of buffers,  distributes and processes the observations, and provides access to the intervals of the buffers.

The first step is to split the data from the manager. The map and the enum don't belong to the manager. Maybe you want to tie them together, in which case you'd make a separate class that owns the map and enum and say call it BufferMap.

Then you can have 2 different classes (or 3 if distributing and processing are separable). So make an ObservationProcessor, and a BufferIntervalCalculator.
Then your 2 methods become:

BufferIntervalCalculator bufferIntervalCalculator(bufferMap);
ObservationProcessor observationProcessor(bufferMap);
observationProcessor.Process(observation);

Type1Interval int1 = bufferIntervalCalculator.calculateInterval<Type1Interval>(BufferId, startTime, endTime);
...
TypeNInterval intN = bufferIntervalCalculator.calculateInterval<TypeNInterval>(BufferId, startTime, endTime);


问:
Finding most Important Node(s) in a Directed Graph
I have a large (≈ 20 million nodes) directed Graph with in-edges & out-edges. I want to figure out which parts of of the graph deserve the most attention. Often most of the graph is boring, or at least it is already well understood. The way I am defining "attention" is by the concept of "connectedness" i.e. How can i find the most connected node(s) in the graph?

In what follows, One can assume that nodes by themselves have no score, the edges have no weight & they are either connected or not.

This website suggest some pretty complicated procedures like n-dimensional space, Eigen Vectors, graph centrality concepts, pageRank etc. Is this problem that complex?

Can I not do a simple Breadth-First Traversal of the entire graph where at each node I figure out a way to find the number of in-edges. The node with most in-edges is the most important node in the graph. Am I missing something here?

答: I've found the following picture a good key for the difference between different measures (although undirected graphs are depicted, some apply to directed as well). Degree centrality [D] is straightforward: who has most in/out links. Eigenvector-centrality [C] captures the notion of indirect influence better. See Centrality on wikipedia for the definitions and details.

ContentLicense: CC BY-SA 3.0


问:
Is this a good implementation of the builder pattern?
I'm trying to design an SQL builder in PHP. I'm trying to make it so that the system could work with different database systems (e.g. Oracle, MySQL, MSSQL). Here's what I've got so far.

First, I have an interface named ISelectQuery which defines a contract which all Select query builders must adhere to:

```<code>interface ISelectQuery{
    public function addTables($tables);
    public function addColumns($columns);
    public function addWhere($column,$operator,$value,$bind = null);
    public function addOrder($col,$dir);
    public function validate();
    public function toString();
    public function getTables();
    public function getColumns();
    public function getWhere();
    public function getOrder();
    public function getBinds();
}
</code>```

Next, I have a class named OracleSelectQuery which is my query builder for Oracle. In the future there could also be MysqlSelectQuery.

```<code>class OracleSelectQuery implements ISelectQuery{
    const EQUALS = '=';
    const NOTEQUALS = '!=';
    const LIKE = 'LIKE';
    const ASC = 'ASC';
    const DESC = 'DESC';

    private $tables = array();
    private $columns = array();
    private $where = array();
    private $order = array();
    private $binds = array();

    //add an array of tables to the query
    public function addTables($tables){
        $this->tables = array_merge($this->tables, $tables);
        return $this;
    }

    //add an array of columns to the query
    public function addColumns($columns){
        $this->columns = array_merge($this->columns, $columns);
        return $this;
    }

    //add a where clause to the query
    public function addWhere($column,$operator,$value,$bind = null){
        $where = array($column,$operator,$value,$bind);
        $this->where[] = $where;
        return $this;
    }

    //add some ordering to the query
    public function addOrder($col,$dir){
        $order = array($col,$dir);
        $this->order[] = $order;
        return $this;
    }

    public function validate(){
        //can't be a valid query if tables aren't defined
        if(empty($this->tables)){
            throw new Exception('Tables not defined.');
        }
        //can't be a valid query if columns aren't defined
        if(empty($this->columns)){
            throw new Exception('Columns not defined.');
        }
        //search through each where clause to see if they are valid
        foreach($this->where as $where){
            if(!in_array($where[1],array($this::EQUALS, $this::NOTEQUALS, $this::LIKE))){
                throw new Exception($where[1].' is not a valid WHERE clause');
            }
        }
        //search through each order by clause to see if they are valid
        foreach($this->order as $order){
            if(!in_array($order[1],array($this::ASC, $this::DESC))){
                throw new Exception($order[1].' is not a valid ORDER BY clause');
            }
        }

        return $this;
    }

    public function toString(){
        //add the columns to the query
        $sql = 'select '.implode(', ',$this->columns).' from ';

        //add the tables
        $sql .= implode(', ',$this->tables).' ';

        //add the where clauses (if where clauses were added)
        if(!empty($this->where)){
            $sql.= 'where ';

            //loop through each where clause
            foreach($this->where as $where){
                //where[0] will be the column, where[1] will be the comparison
                $sql.= $where[0].' '.$where[1].' ';

                //if where[2] has a '?' in it, it must be a bind
                if(strstr($where[2],'?') !== false){
                    //give the bind variable a unique name, by counting the number of binds already created
                    $bindName = ':bind'.count($this->binds);

                    //replace the '?' with the bind variable name
                    $sql .=' '.str_replace('?',$bindName,$where[2]);

                    //add the bind variable name and value to the list of binds - this can be used by the database connection
                    $this->binds[] = array($bindName,$where[3]);
                }else{
                    //if it's not a bind variable, add the simle value
                    $sql .= $where[2];
                }

                //don't forget to add the and at the end
                $sql .= ' and ';
            }

            //remove the last ' and '
            $sql = substr($sql,0,-5);
        }

        //add the order clauses (if they exist)
        if(!empty($this->order)){
            $sql .= ' order by ';

            //loop through each order clause and add it to the sql
            foreach($this->order as $order){
                $sql .= $order[0].' '.$order[1].', ';
            }

            //remove the last comma
            $sql = substr($sql,0,-2);
        }

        //return the finished query to the client
        return $sql;
    }

    //getters to allow client to inspect query later
    public function getTables(){
        return $this->tables;
    }

    public function getColumns(){
        return $this->columns;
    }

    public function getWhere(){
        return $this->where;
    }

    public function getOrder(){
        return $this->order;
    }

    public function getBinds(){
        return $this->binds;
    }
}
</code>```

You can then use the following code to generate SQL:

```<code>//create a new select query
$select = new OracleSelectQuery();
$sql = $select->addTables(array('table1','table2'))
                            ->addColumns(array('col1','col2'))
                            ->addWhere('col1',OracleSelectQuery::LIKE,'?','value')
                            ->addOrder('col1',OracleSelectQuery::ASC)
                            ->validate()
                            ->toString();
echo $sql;
</code>```

My question is - is this a good implementation of the builder pattern? Is there any way you would improve it?

答:
I agree with @BartvanIngenSchenau : add the validate inside toString. Also:

toString would be much better be renamed to build, to more strongly suggest a Builder Pattern.

Unlike C#, in PHP the convention is to NOT use the letter I in interface names. Instead something like QueryInterface is the community wide convention.

getters are not necessary

maybe mark the validate method as private. From what I now, in the context of the Builder Pattern, the method that validates the state is never called explicitly by the user of the pattern

If you implemented this because you need it and not for a purely intellectual exercise, then I would recommend not to re-invent the wheel and to use a dedicated functionality instead, like Doctrine DBAL, which has a Query Builder included.


问:
Deciding on a software license for a C++ API
I have designed and developed a C++ API. Its dependencies are:

BLAS - custom license - http://www.netlib.org/blas/#_licensing

LAPACK - modified BSD - http://www.netlib.org/lapack/LICENSE.txt

GLPK - GPL

Mytonly restriction, besides being properly quoted as the author, is that I DO NOT want those who download it from my GitHub to be able to share the code among them; I want them to download it from my GitHub.

Based on my dependencies, can I do that?

If I can, which license would work?

答:
As your API depends on a library that is licensed with the GPL license, the answer to your first question is: No, you can not apply those restrictions to your API.

The GPL is a copyleft open-source license. This means that any project that is based upon (or links to) GPL code must be made available under the same license (this is the copyleft nature of the GPL).

The fact that the GPL is open-source means that everyone has the right to make changes to the software covered by an open-source license and distribute a modified or unmodified version of that software.

If your reason for wanting to restrict who can distribute your project is to prevent multiple incompatible versions from being distributed at the same time, then you might look to trademark protection.

If you register a trademark on the name of your API, then you have full control over who gets to distribute software with that name. This is independent of the copyright license that applies to the software.

If someone wants to fork your API without your permission, they will have to rename their version to avoid infringing on your trademark.


问:
How to calculate number of indirect dependencies of a class?
Most of the static code analysis tools which analyse class dependencies generate dependency pairs of classes where each pair represents a direct dependency between two classes. Given those dependency pairs, it is straight forward to calculate number of direct dependencies of a particular class. However, if we have to compute number of indirect dependencies of a class, I realized that the algorithm is fairly complex. Let me clarify what I mean by indirect dependency:

We have following direct dependency class pairs:

Class A depends on Class B

Class B depends on Class C

Class B depends on Class D

In this case, class A depends directly on class B and indirectly on classes C and D.

I would define number of direct dependencies for class A as 1 and number of indirect dependencies for class A as 2.

I would like to compute indirect dependencies for each and every class in the systems that I analyse.

The complexity arises mainly due to cyclic dependencies.

For example, if we were to compute number of indirect dependencies for class A:

Scenario 1:

A -> B

B -> C

C -> D

D -> B

Scenario 2:

A -> B

B -> C

B -> D

C -> E

D -> F

E -> G

F -> G

G -> H

Scenario 3:

A -> B

B -> C

C -> A

Can this be solved by using graph theory? For example, represent all dependency pairs using a directed graph and calculate recursive sum of outdegrees of adjacent nodes. Any other ideas are welcome.

Let me know what is the best way to get it.

答:
Calculating the direct dependencies is very straightforward. So for your purposes I'd recommend finding the count of all dependencies, then if you're interested in indirect only, you can just subtract the number of direct from the total.

The algorithm isn't too tricky, and in pseudocode would look something like:

```<code>count = 0
visited = [ ]
toVisit = [ startNode ]
while(toVisit not empty)
{
    current = toVisit.Pop
    for(dependency in current.dependencies)
    {
        if(dependency not in visited)
            toVisit.Push(dependency)
    }
    visited.Push(current)
    count++;
}
</code>```

You're just traversing the graph, keeping track of all nodes already visited to make sure you don't revisit them (avoiding issues arising due to circular dependencies).

Body:
Calculating the direct dependencies is very straightforward. So for your purposes I'd recommend finding the count of all dependencies, then if you're interested in indirect only, you can just subtract the number of direct from the total.

The algorithm isn't too tricky, and in pseudocode would look something like:

count = 0
visited = [ ]
toVisit = [ startNode ]
while(toVisit not empty)
{
    current = toVisit.Pop
    for(dependency in current.dependencies)
    {
        if(dependency not in visited)
            toVisit.Push(dependency)
    }
    visited.Push(current)
    count++;
}

You're just traversing the graph, keeping track of all nodes already visited to make sure you don't revisit them (avoiding issues arising due to circular dependencies).


问:
Why Session has implemented this way in Asp.net
I'm not a Asp.net/C# developer myself but recently had to slightly refactor a Asp.net/C# project and I had to use Session at some point. When working with the session, regardless of the data type that I was specifying for the session variable, I had to cast the session variable any time I needed to access it.

```<code>Session["index"] = 0;
Session["index"] = Session["index"] + 1; // throws exception
Session["index"] = ((int)Session["index"]) + 1; // it works here
</code>```

Asking my C# developer colleagues, it seems that the Session is somehow an object that covers up the actual data type of the variable, apparently without losing it, but for some reason you still need to cast it anyway any time you want to access it.

I'm not sure if that's the case or not or even if I have understood it properly, but what I don't understand is why it has to be implemented in a way that the developer has to cast it before using it. As my colleagues say, that's because you can basically have a dynamically typed session object, at run-time.

What I'm thinking is, first, why you need to have such a feature only for the session, in a statically typed language like Asp.net/C#? For example, what is the use case of defining a "session" variable as an integer, but then put string on it at the run-time? Is there any practical use case and requirement for such a feature, not only in Asp.net but any other language?

Second, if we assume that the session variables also has to be statically typed, then is it "technically" possible to implement Asp.net's session in a way that when you define a session variable like below, the compiler allocates the memory in the heap, keep the data type next to it and simply eliminates the need for casting it each time?

```<code>Session["index"] = 0; // integer type, available at compile-time
</code>```

What would happen if you try to assign a string to this integer variable? Well, like everything else in a statically typed language, you will get an exception.

Am I missing anything here? I simply can't understand why such a design decision has been made by the Asp.net development team and how the developer could benefit from that. Also wondering if there is anything related to how other languages like Java or C++ have implemented sessions, either directly in the language itself or via a library, so it led the Asp.net team as well to implement session like that?

Update #1

Just to clear the air, my main question is why the Session has implemented in this way? What are the benefits of having a session like this -- whatever it is, rather how it has implemented -- even though I'm looking to know that as well.

Update #2

Regarding @JacquesB comment: "You have to be able to save all kinds of different objects in a Session, so the type has to be Object, there is no other option"; Why the following code:

```<code>Session["index"] = 0;
Session["name"] = "abc";
</code>```

Can't be translated, by compiler, at the compile-time, to something like this:

```<code>int SessionIndex = 0;
string SessionName = "abc";
</code>```

I don't get why "there is no other option". It's a computer program after all, not anything magical, or am I still missing something?

答:
The underlying issue is not Session or Asp.Net specific, it is a fundamental issue in how collections in statically typed languages work. The Session object is designed to let you store objects of any type. This means the static type of the stored items must be Object. So Session is equivalent to a Dictionary<string, Object>. Since the compiler can only know that the type of the item is Object, you have to explicitly cast to a more specific type in order to perform any operation (and that cast may of course fail at runtime if you get the wrong type.)

Now you ask why the compiler is not smart enough to recognize that:

```<code>Session["name"] = "abc";
</code>```

means that the entry with key "name" will be of type string. This cannot work because the name of the key is an expression with a value which may be unknown at compile time. Eg.

```<code>Session[Datetime.Now.ToString()] = "abc";
</code>```

There is no way the compiler can figure this out in the general case, even if it is theoretically possible in some very specific cases.

To explain a bit more generally: You have to distinguish between the type of a value at runtime, and then the type that the compiler is able to determine at compile time.

A value always have a specific type at runtime, and this type is (as you suggest) stored together with the value, so you can always inspect the actual type of a value with the GetType() method.

But in a statically typed language, the type checking happens at compile time, and at that stage the compiler is not always able to know the actual type of all values. Take this example:

```<code>object x = "abs";
int l = x.Length; // !Compile error
</code>```

At runtime, the type of the value in x is String, but the compiler have to rely on the declared type of x with is Object. And since Object does not have the property Length, you get a compile error.

Now you might think that compiler should be smart enough to realize that x is actually a String in this case, but this will not work in the general case, since x might be assigned say an integer in a different part of the program, so the actual type might change through the running of the program. The only thing the compiler can guarantee is that the type of x will be Object or a subtype of Object, because that is the declared type.

In this particular case you know more than the compiler, because you realize that x is a String, even though the declared type is less specific. This is where we can use a cast: When we know the runtime type better than the compiler. A cast does not change the type of a value, rather it just informs the compiler to assume a certain more specific type. So you can write:

```<code>int l = ((string)x).Length;
</code>```

A cast will of course fail at runtime in case the actual type of the value in x is not string.

Body:
The underlying issue is not Session or Asp.Net specific, it is a fundamental issue in how collections in statically typed languages work. The Session object is designed to let you store objects of any type. This means the static type of the stored items must be Object. So Session is equivalent to a Dictionary<string, Object>. Since the compiler can only know that the type of the item is Object, you have to explicitly cast to a more specific type in order to perform any operation (and that cast may of course fail at runtime if you get the wrong type.)

Now you ask why the compiler is not smart enough to recognize that:

Session["name"] = "abc";

means that the entry with key "name" will be of type string. This cannot work because the name of the key is an expression with a value which may be unknown at compile time. Eg.

Session[Datetime.Now.ToString()] = "abc";

There is no way the compiler can figure this out in the general case, even if it is theoretically possible in some very specific cases.

To explain a bit more generally: You have to distinguish between the type of a value at runtime, and then the type that the compiler is able to determine at compile time.

A value always have a specific type at runtime, and this type is (as you suggest) stored together with the value, so you can always inspect the actual type of a value with the GetType() method.

But in a statically typed language, the type checking happens at compile time, and at that stage the compiler is not always able to know the actual type of all values. Take this example:

object x = "abs";
int l = x.Length; // !Compile error

At runtime, the type of the value in x is String, but the compiler have to rely on the declared type of x with is Object. And since Object does not have the property Length, you get a compile error.

Now you might think that compiler should be smart enough to realize that x is actually a String in this case, but this will not work in the general case, since x might be assigned say an integer in a different part of the program, so the actual type might change through the running of the program. The only thing the compiler can guarantee is that the type of x will be Object or a subtype of Object, because that is the declared type.

In this particular case you know more than the compiler, because you realize that x is a String, even though the declared type is less specific. This is where we can use a cast: When we know the runtime type better than the compiler. A cast does not change the type of a value, rather it just informs the compiler to assume a certain more specific type. So you can write:

int l = ((string)x).Length;

A cast will of course fail at runtime in case the actual type of the value in x is not string.


问:
Should I include `assembly` as programming language in the CV?
In the answer for one question someone wrote that assembly is not a language, it's a process. I tend to agree, since the assembly "language" is dependent on the architecture it will run on, which may differ quite a bit from one CPU to another.

So if you've written assembly for one architecture, does that mean you can include it in the CV under merely assembly along with the other programming languages? Or do you explicitly say that you've written assembly for that particular architecture?

EDIT: Changed 'dabbled' to 'written'. English isn't my native language and I misunderstood the term, thinking it meant that you've used it a lot instead of just a bit.

答:
Write assembler and include the particular CPU architecture. Otherwise you give indication that you didn't understand assembler.
Also consider to including assembler if it's relevant for new job.

ContentLicense: CC BY-SA 2.5


问:
Semantic versioning in Agile
Let's say I have 14 days sprint iterations where I have several stories for new features, few improvements and some bugs to fix. I also deploy those changes when they are ready, I'm not waiting for end of sprint.

My problem is - how to track semantic versioning of products developed and maintained like this? If there will be release every 14 days it will be easy, I will increase version number and note all changes in changelog. But what if changes are deployed continuously? Should there be version increased everytime something is deployed? Or should I wait until sprint ends and after this, make some "resume" and increase version number just once per iteration independently on actual deployment? What are best practices for semantic versioning in Agile?

EDIT: To better explain my needs, I want changelog for stakeholders in a first place. I don't think they will be interested in new record in changelog after every change deployed.

答:
I would use build numbers. Usually a build number would correspond to the highest version of the version control system. If mondays build number was 1745 and there has been checked 5 changes in during tuesday, tuesday evenings build number would be 1750.

Then make a short summary for what has changed between 1745 and 1750.

Then every time you update the version number of your system you can add up all the short summaries from the builds to get the changes from the last version number to the new.

Title: Semantic versioning in Agile


问:
Should domain model be intelligent or there must be services, which operate it?
I'm building a web-app for a licensing service. My domain models are Licenses, and they can be of two types at the moment: server and client license. They are almost same, except server license has softwareId field, and client license has hardwareIdArray (client licenses can be registered to multiple clients).

So, I have a base model License with it's children: ClientLicense and ServerLicense, which bring additional fields.

Models of each type are fetched by respective Repositories (I'm using TYPO3 Extbase framework, where it is standard and recommended way).

Now comes the interesting part: each license has some additional info, which I can't persist (well, I can, but only in temp cache), but instead should fetch it from REST service (e.g. "expirationDate", which may be changed outside of my web-app). And for each type of license this additional info may be different and may be fetched by different method in REST api. Also each license type has different activate() REST method. At same time there are common REST methods, like getLicenseFile().

So, I decided to hide all this internal stuff under LicenseService class, which is recommended to communicate by Controllers or other classes, that need some license info. LicenseService itself communicates to LicenseRestApi, which contains some low-level functionality to perform REST requests.

And here comes a question: who should know about each license type specific functionality? F.e. when a controller asks a service to getAllLicenses($user), is it a Service, who should determine a type of license and then perform calls to respective Repository and appropriate methods in RestApi; or a license should know everything about itself and call RestApi; or some new classes, like ClientLicenseProcessor and ServerLicenseProcessor, to which should LicenseService communicate and all the communication with RestApi should be within these processors, so in this case LicenseService will act as FactoryMethod for creating appropriate processor?

My goal is to hold specific type logic in one place and not spread it between several classes.

答: The service shouldn't make any decisions or you end up with a anemic domain model. Your license aggregate should make the decisions. If the license aggregate needs to call a web service you pass an instance of a helper for that service to the method on the aggregate. It can them choose to use them if it so wishes.</p>


问:
When's a resource a resource?
So I have a rendering engine, and I have a resource manager that adds classes that derive from type 'Resource'. It's a very flexible and generic resource manager, of which only one can exist (it is a static class). Thus, a class ShaderProgram or Camera can easily be added like so:

```<code>    rm::add("textShader",
        new ShaderProgram("assets/shaders/renderText.vert",
                          "assets/shaders/renderText.frag", true, true));

    rm::add("fpsCamera",
            new FPSCamera(glm::vec3(0.f, 0.f, 20.f), 45.f, 4.f / 3.f, 1.f, 1000.f));
</code>```

Now, this may seem quite straightforward; but a theoretical question I ask myself is: when is a resource a resource? How does one differentiate between something that ought to be stored (e.g. a resource) vs. something that should not be stored (e.g. non-resource)?

For instance, I know that I will be using my ShaderProgram and Camera as well as Texture (all of type Resource) a lot. In order for me to get the explicit type of a Resource, I do the following:

```<code>convert(Camera*, rm::get("fpsCamera"))->func(); // call Camera's func()
</code>```

Thus, I know that it if I need to reuse something over and over again I would have to store it in the resource manager.

When it comes to another class, however, it gets a bit more complicated. I have two other classes: Renderable and Scene. The relationship between the two is very intimate insofar that a Renderable is an abstract class for renderables such as Sprite, Model etc; and Scene is simply a container of a number of Renderables. Thus, in a graphics application it is likely that I will be loading scenes and unloading them to free up resources when required. But I am not sure whether Renderable should derive from type Resource or whether Scene should derive from type Resource (thereby calling Scene a resource) or whether both should simply be a Resource. If a Renderable were a resource then that means it can be accessed by anyone as easy as:

```<code>convert(Model*, rm::get("someRandomModel"))->randomFunc();
</code>```

Now before you yell at me about type-safety in the above function, I'd like to reassure everyone that the compiler checks against the type and sees if the called function is resolved. It's a dynamic_cast after all.

Anyway, the dilemma thus continues and at first thought I can only assert that Renderable could be a Resource only IF we want to reuse the renderables in question. Thus, if I were to add a Model to the resource manager then that means it is available everywhere in the program. But, it can't be retrieved unless you know the ID of that Resource. Thus, it is entirely possible for me to reuse a Model object to replace an existing Mesh inside it.

Without getting too technical, I again ask the simple question: When is a resource a resource, and where do we draw the line?

答:
Though there is no "official" definition of a "resource", the term is generally used for anything that your program has to explicitly acquire before use, and possibly release after use, where the act of acquiring and releasing is either expensive or complicated enough that we want to avoid doing it more than we have to. Typically, this includes any file we have to open (image, model, mesh, sound, music, data, etc.), any hardware we need (audio context, graphics context, etc), and any network connections we need.

Generic resource managers are useful because they can abstract away the need to worry about exactly when to acquire and release the resource, instead enforcing some straightforward rule like "acquire it the first time someone asks for it and release it after no references to it remain in scope" which prevents performance problems like reopening the same file every single time we want to use it, instead of simply leaving it open until we're done with it.

Given this definition of a "resource", your Renderables probably do not qualify. Many Renderables will need to refer to a resource, but that doesn't mean they are resources themselves. A Scene may need lots of data to be rendered properly, but it doesn't have to contain all of that data itself. For instance, it can refer to graphics assets via filenames, or via some custom object the resource manager provides. That way, the Scene itself is a relatively lightweight object that's no harder to construct than any other C++ object, so it would not benefit from being managed as if it was a heavyweight resource.

In addition to that theoretical argument, I see two other red flags with your specific proposal. It's possible you didn't mean these that seriously and these responses will amount to nitpicks, but I believe they're worth mentioning regardless.

First, the only benefit you cite for making Renderable or Scene derive from Resource is that "it can be accessed by anyone". That is not a benefit. While "global variables are evil" may be overly dogmatic and simplistic, you should generally make an effort to restrict access to a variable to those parts of the code which actually need it. Does the Scene rendering logic need to know about the resource manager? Probably not. The code to draw individual Renderables probably does, but not the code to traverse scene graphs.

Second, in most cases, the whole point of making a base class B for classes X and Y is so that you can call b->foo() without caring whether b is of type X, Y or Potato. If you have to do a dynamic_cast to ensure "type safety", that means you probably do care what concrete type b has, which means you probably aren't gaining anything from the common base class. If the resource manager is requiring you to do dynamic_casts to use the resources it managers, I would consider that a serious flaw with the manager; generic code in C++ should usually rely on templates rather than dynamic_casts for its type safety.

Title: When's a resource a resource?


问:
Automatically reverting commits that fail the build
A colleague of mine told me that he is thinking in making our CI server to revert commits that failed the build, so the HEAD in master is always stable (as in passing the build at least).

Is this a best practice or it may be more problematic than just leaving master broken until the developer fixes it?

My thinking is that reverting the commit will make more complex the task of readding the commit and fix (developer will have to revert the revert and then commit the fix, which will also clutter the git log) and we should just leave the commit and then commit the fix. Although I see some advantages in having master stable, this revert of failing commits does not convince me.

edit: Doesn't matter if it is master or any other development branch, but the question stays the same: should the CI system revert a commit that failed the build?

another (lenghty) edit: Ok, we're using git in a strange way. We believe that the concept of branches goes against real CI, because committing to a branch isolates you from the other developers and their changes, and adds time when you have to reintegrate your branch and deal with possible conflicts. If everyone commits to master this conflicts are reduced to the minimum and every commit passes all tests.

Of course, this forces you to push only stable (or you break the build) and program more carefully to not break backwards compatibility or do feature-toggling when introducing new features.

There are tradeoffs when doing CI this or that way, but that is out of the scope of question (see related question for this). If you prefer, I may reword the question: a small team of developers work together in a feature branch. If one developer commits something that breaks the build for that branch, should the CI system revert the commit or not?

答:
I would be against doing this for the following reasons:

Any time you set up an automated tool to change code on your behalf, there is the risk that it will get it wrong, or that a situation will arise where you need it to stop making that change (e.g., the latest version of Google Mock had a bug in it, so it's not your code failing) and you have to waste time reconfiguring it. Plus, there's always a slight risk that the build will fail because of a bug in the build system, rather than a bug in your code. For me, CI is about gaining confidence that my code is correct; this would merely turn it into another source of potential problems for me to worry about.

The kinds of bugs that break "the build" should be silly mistakes that take very little time to fix (as you've indicated in a comment, this is true for you). If more subtle and complicated bugs are regularly making it onto master, then the correct solution is not to "fix it faster", it's to be more careful when reviewing feature branches before they get merged.

Leaving master unbuildable for a few minutes while the bug gets fixed properly doesn't hurt anyone. It's not like the CEO will personally check out master and publish the code straight to clients at any random moment (at least, hopefully not without your involvement). In the highly unlikely event that you need to release something before you can fix the bug, then you can easily make the decision to revert manually before publishing.


问:
Collections.sort question
My question maybe related to this question - Encapsulating Internal Data Structure

I have a class LCTile.java which contains a Coordinate.java class. Coordinate.java  that contains latitude and longitude(essentially a Point2D.java). Now I wish to sort the coordinates by latitude or longitude for which I have already developed a CoordinateComparator class. The Java API requires you pass in the List to be sorted and the Comparator i.e. Collections.sort(List list ,Comparator comparator).
My question is the following - In order to sort the various tiles by latitude or longitude I have to obtain all the coordinate classes in a list from the original LCTile class and then pass them to the Collections.sort interface  and then map them back to the original tile(s) after the sort operation is over.
Is the encapsulation of the Coordinate class inside the LCTile absolutely essential or can this be done in a different way ?

答:
You can create a comparator that compares the coordinates of the tile. In java 8 there is a helper function for that:

```<code>Comparator<LCTile> cmp = Comparator.comparing(
         LCTile::getCoordinate,
         CoordinateComparator.instance);
</code>```

Then you can pass that with the list of tiles to Collections.sort.

Title: Collections.sort question

Body:
You can create a comparator that compares the coordinates of the tile. In java 8 there is a helper function for that:

Comparator<LCTile> cmp = Comparator.comparing(
         LCTile::getCoordinate,
         CoordinateComparator.instance);

Then you can pass that with the list of tiles to Collections.sort.


答:
I'd file that somehow under 'architecture experience', perhaps something like this:

"Successfully ported (kernel or
  subsystem) to [arch], in depth
  knowledge of [arch] assembly."

I'd be quite concise in your 'goals' area, explicitly indicating what you hope to work with. It would suck if you got hired, then got handed a stack of ageing junk that had to be ported.

Title: Should I include `assembly` as programming language in the CV?

Body:
In the answer for one question someone wrote that assembly is not a language, it's a process. I tend to agree, since the assembly "language" is dependent on the architecture it will run on, which may differ quite a bit from one CPU to another.

So if you've written assembly for one architecture, does that mean you can include it in the CV under merely assembly along with the other programming languages? Or do you explicitly say that you've written assembly for that particular architecture?

EDIT: Changed 'dabbled' to 'written'. English isn't my native language and I misunderstood the term, thinking it meant that you've used it a lot instead of just a bit.


答:
Is this a best practice or it may be more problematic than just leaving master broken until the developer fixes it?

It is problematic. A person deciding "the master HEAD is broken; I will revert the top change" is completely different than the CI system doing the same.

Here are a few disadvantages:

Errors in the automated reversal process will screw up the repository;

this assumes a single changeset (the topmost) screwed up the build (which is unrealistic)

Maintainers will have more work to do to fix the issue, than just investigation and commit (they will also have to look at reverse history)

We believe that the concept of branches goes against real CI, because committing to a branch isolates you from the other developers and their changes, and adds time when you have to reintegrate your branch and deal with possible conflicts.

This belief (branches vs. CI) is incorrect. Consider keeping one stable branch, where you commit only unit tested changesets. The rest (feature branches and local branches) should the responsibility of each developer and not part of your CI policy in any way.

In feature branches you want to be isolated from other developers. This allows you to:

perform exploratory coding

experiment with the code base

perform partial commits (effectively commit non-working code) to set up backup points (in case you screw up), to create more meaningfull change history (through commit messages), and to back up your work and switch completely to something else (in the time it takes you to write "git commit && git checkout ")

perform low-priority tasks that take a long time (e.g. you want to perform a refactoring that alters all 80 classes of the data layer: you change two per day, until you change all of them an the code compiles (but you can do this without affecting anyone until you can make a single commit).

If one developer commits something that breaks the build for that branch, should the CI system revert the commit or not?

It shouldn't. Committing stable code on your CI branch is a responsibility of the committer, not an automated system.

Title: Automatically reverting commits that fail the build

Body:
A colleague of mine told me that he is thinking in making our CI server to revert commits that failed the build, so the HEAD in master is always stable (as in passing the build at least).

Is this a best practice or it may be more problematic than just leaving master broken until the developer fixes it?

My thinking is that reverting the commit will make more complex the task of readding the commit and fix (developer will have to revert the revert and then commit the fix, which will also clutter the git log) and we should just leave the commit and then commit the fix. Although I see some advantages in having master stable, this revert of failing commits does not convince me.

edit: Doesn't matter if it is master or any other development branch, but the question stays the same: should the CI system revert a commit that failed the build?

another (lenghty) edit: Ok, we're using git in a strange way. We believe that the concept of branches goes against real CI, because committing to a branch isolates you from the other developers and their changes, and adds time when you have to reintegrate your branch and deal with possible conflicts. If everyone commits to master this conflicts are reduced to the minimum and every commit passes all tests.

Of course, this forces you to push only stable (or you break the build) and program more carefully to not break backwards compatibility or do feature-toggling when introducing new features.

There are tradeoffs when doing CI this or that way, but that is out of the scope of question (see related question for this). If you prefer, I may reword the question: a small team of developers work together in a feature branch. If one developer commits something that breaks the build for that branch, should the CI system revert the commit or not?


答:
The CI should never alter the commit history of the repo.

The correct solution here is for no commits to be added to master branch if they haven't been tested and verified.

Do you work on feature branches, have the CI run automatically on those, and if the builds fail, don't merge them into master.

You can have an additional build that tests merges if those are a concern, by running on the feature branch, and during the build merging master/integration/whatever into the local branch, then running tests.


问:
Should well-known business ID of an entity be represented with a dedicated type in DDD/OOP?
In practical terms it means using an custom (immutable) class over a string or some other primitive type.

Examples:

Publishing: International Standard Book Number.

Finance: International Securities Identification Number.

Advantages:

Can ensure the format of an identifier.

Becomes a first-class member of the model.

Disadvantages:

Adds persistence friction (e.g. Entity Framework).

More code.

答:
If you can give the class enough useful functionality to justify the added complexity of not being a string, then do it. For identifiers like ISBN and ISIN, I suspect this is not the case.

For an identifier class to be useful, I'd expect it to look something like this:

```<code>class ISIN {
    fromCUSIP()
    fromRawISINString()
    toString(ISIN::FormatType)
    getExchange()
    getCountryCode()
    getLastFourDigits()
    getWhateverCode()
    ...
}
</code>```

If instead it looks more like this:

```<code>class ISIN {
    getString()
    setString()
}
</code>```

Then I'd ditch the class entirely, use regular strings everywhere, and make sure I consistently use "isin" in all the relevant variable names.

Note that in some languages, adding a new type has almost no "added complexity" in typical programs, in which case you'd be encouraged to create the new type even if it had no functionality at all. But this is not the case for most traditional OOP languages like C++.

Body:
If you can give the class enough useful functionality to justify the added complexity of not being a string, then do it. For identifiers like ISBN and ISIN, I suspect this is not the case.

For an identifier class to be useful, I'd expect it to look something like this:

class ISIN {
    fromCUSIP()
    fromRawISINString()
    toString(ISIN::FormatType)
    getExchange()
    getCountryCode()
    getLastFourDigits()
    getWhateverCode()
    ...
}

If instead it looks more like this:

class ISIN {
    getString()
    setString()
}

Then I'd ditch the class entirely, use regular strings everywhere, and make sure I consistently use "isin" in all the relevant variable names.

Note that in some languages, adding a new type has almost no "added complexity" in typical programs, in which case you'd be encouraged to create the new type even if it had no functionality at all. But this is not the case for most traditional OOP languages like C++.


答:
For typical release management, you will want a build number being generated by your build system so that the DLLs are versioned every time they are deployed. This will ensure you can later check which version is deployed on a given server.

Your 'marketing' version, which is usually put in release notes or published to your site should not be updated each version. Those release notes should be accumulated and grouped together, likely timed with the end of your sprint.

Title: Semantic versioning in Agile

Body:
Let's say I have 14 days sprint iterations where I have several stories for new features, few improvements and some bugs to fix. I also deploy those changes when they are ready, I'm not waiting for end of sprint.

My problem is - how to track semantic versioning of products developed and maintained like this? If there will be release every 14 days it will be easy, I will increase version number and note all changes in changelog. But what if changes are deployed continuously? Should there be version increased everytime something is deployed? Or should I wait until sprint ends and after this, make some "resume" and increase version number just once per iteration independently on actual deployment? What are best practices for semantic versioning in Agile?

EDIT: To better explain my needs, I want changelog for stakeholders in a first place. I don't think they will be interested in new record in changelog after every change deployed.


问:
Should a web service return an error message if it receives unknown parameters?
I have a web service which allows to retrieve users: http://example.com/users. It returns a list of users.

That service accepts a number of parameters (age, gender) to select which users to retrieve. Examples:

http://example.com/users?age=34

http://example.com/users?gender=male

Should that service return an error message  if the client is passing an unknown parameter? Example:

```<code>>>> GET http://example.com/users?cylinders=16
<<< 400 Bad Request
<<< { 'message' : "Invalid parameter 'cylinders'" }
</code>```

(To me it's clear that a web service should validate the parameters it receives, but the case of unknown parameters is not clear to me)

答:
Technically, such checking requires an additional step. You have to list all the parameters, and compare this list with the list of allowed ones. Then, if you decide to accept an additional parameter, you have to change this list, requiring even more work. All this code has to be tested as well.

What's the benefit? The benefit is that a programmer who made a typo such as:

```<code>                             ↓↓
http://example.com/users?gendre=male
</code>```

will immediately see a helpful error message, instead of receiving the list of all users and wondering why is the filter not working. That's great, and I wish all APIs were that helpful and programmer-friendly.

It's up to you to decide whether this benefit is worth the effort of writing additional code and tests.

One of the cases where you shouldn't care is when you develop the client libraries yourself. If you provide those libraries in most popular languages (Java, Python, Ruby, C++, C#, ObjectiveC, PHP), it may not be that useful to handle the case where a non-supported parameter was specified.

Body:
Technically, such checking requires an additional step. You have to list all the parameters, and compare this list with the list of allowed ones. Then, if you decide to accept an additional parameter, you have to change this list, requiring even more work. All this code has to be tested as well.

What's the benefit? The benefit is that a programmer who made a typo such as:

                             ↓↓
http://example.com/users?gendre=male

will immediately see a helpful error message, instead of receiving the list of all users and wondering why is the filter not working. That's great, and I wish all APIs were that helpful and programmer-friendly.

It's up to you to decide whether this benefit is worth the effort of writing additional code and tests.

One of the cases where you shouldn't care is when you develop the client libraries yourself. If you provide those libraries in most popular languages (Java, Python, Ruby, C++, C#, ObjectiveC, PHP), it may not be that useful to handle the case where a non-supported parameter was specified.


答:
Let's agree on terms first.

I personally use the terms Continuous Build and Continuous Integration to distinguish two different scenarios:

Continuous Build: a tool that checks periodically if the repository changed since the last build, and build/test if it did.

Continuous Integration: a tool that takes Pull Requests and validate them against the latest head prior to making them visible.

The latter, Continuous Integration, means that the repository it protects is always green1: it is strictly better.

Your question only really makes sense for Continuous Build, so I will answer assuming this is your setup.

1: Environmental causes can also screw up a build, for example a test with a hard-coded year (2015) may start to fail January of 2016, a disk can get full, ... And of course there is the plague of unstable tests. I haughtily ignore those issues here; else we'll never get anywhere.

If you have a Continuous Build setup, you can indeed automate reversal of commits that may have broken the build, however there are several subtleties.

You cannot actually strip the commits: other co-workers might have already checked them out and will push them back in the next time they attempt to commit. Instead, a reversal should be committing a reverse diff. Oh, and co-workers will hate you for reverting their work when it was correct as they'll have to find a way to push it back again...

You cannot actually only strip the last commit (it's a merge), but need to strip all commits... up to a certain point. For example, the last known good commit (beware when boot-strapping the system).

You need to think about external causes (environmental issues), and avoid a setup that reverts everything to day 0. Thankfully, reverting to the last known good commit sidesteps this issue.

You need to think that the last known good build might no longer build (environment issues), in which case it is likely that all further commits will be reversed. Ideally, in case of failure, and before reverting, you would checkout the last known good build, and re-test it. If it passes, revert, otherwise, raise an alert.

Note that with this system, in case of an unstable test or a co-worker often committing crap, many good commits will get reversed. Your co-workers will then hate you.

Hopefully my horror tale has exposed the issues of allowing a broken repository and you will now implement a proper Continuous Integration pipeline where PR are never directly pushed to the repository but instead queued up for merging in a work queue, and integrated one at a time (or by roll-ups):

fetch head of repository locally

apply pull request(s)

build and test

in case of success, push to repository, otherwise mark as failing

move to next requests

Having attempted both, this is strictly better.


问:
What is an example of a good SMART objective for a programmer?
Following on from this question, I wondered if folk might be able to suggest some samples of what might be considered a "good" objective in a periodic review cycle for a programmer?

Let's define SMART from the most popular definitions in the Wikipedia entry:

Specific

Measurable

Attainable

Relevant

Time-bound

答:
Since I'm about to go into an objective-setting conversation with my boss, I thought I'd add a few examples that are similar to some I'm considering suggesting for myself:

Increase test coverage for code in Project X to at least 95% by March 31st.

Complete and distribute first draft of Project Y Architecture document by April 30th

Collect review comments for architecture document, update where necessary and issue v1.-0 of document by June 30th

I expect additional work to materialise within the times I've specified (it always has before, after all) and that work may have an effect on the "Timely" aspect in particular. That shouldn't be a problem: objectives should be reviewed regularly to make sure that they continue to meet the "Achievable" criterion. I'll need to make sure that I keep my manager in the loop on this - nobody likes unpleasant year-end surprises...


答:
If the classic semantic versioning scheme "MAJOR.MINOR.PATCH" makes sense, depends on to whom you deploy, and especially when and how often you deploy to the end user. The scheme is most useful if you work with stable release "4.5", where you start with as 4.5.0. The versions 4.5.1, 4.5.2, and so on contain only bug fixes, whilst you internally already work on version 4.6.

For example, if you provide a "stable branch" to your end user, give it a version 4.5.0 for the initial deployment, and 4.5.1, 4.5.2 whenever you release a patch. In your internal "agile" development and mid-sprint deployment, you can already have a version 4.6, just call it a "beta version". Whenever you deploy it in mid-sprint, add the auto-generated build number like "4.6.beta build 123". When your sprint ends, assign it "4.6.0", and switch the version number for the next sprint internally to "4.7". Starting with ".0" is only a convention, you can also use the ".0" for tagging beta-versions, and start with ".1" for your end users. IMHO the word "beta" is much more expressive, telling everyone the sprint "is not completed yet".

If you release a full end-user change log with each beta version is up to you, but at least at the end of the sprint the change log should be completed, and whenever you provide a bugfix to the end user, you should also update the history documents.

You will find the strategy of releasing two separated branches, one "stable" branch with semantic version numbers, and a "development branch" marked with build numbers or something similar, in lots of open source products like Inkscape, Firefox or 7-zip.

If, however, you do not work with separate stable and development branches, and release a new version to you end user daily, you should also increment a version number daily. For such a case, the version numbers "4.5.1", "4.5.2", ... will probably reflect your individual deployments, and do not indicate the difference between bug fixes and other changes. That can be ok, it is just not classic "semantic versioning" any more. In this scenario, you could also deploy versions 4.5, 4.6, 4.7, 4.8, that gives no real difference.

Concerning your question about entries in your changelog: IMHO when something is visible to the end user, it is worth an entry in the changelog, as soon as you deploy the change. For example, if you use feature toggles and make changes to some half-baked feature which is not activated yet to the user, that does not belong into a changelog. If you do only refactoring, with no visible change to user, that does not belong into a changelog. If you fix a bug which could have affected some users, that belongs definitely into the changelog - and it should be mentioned there at the same time when you deploy the bugfix. And it does not matter if you release daily or monthly or yearly.

Title: Semantic versioning in Agile


问:
In what situations would it be technically 'impossible' to release a system as open source?
While there are certainly many economic, social and practical decisions to be made when deciding whether a system should be open source, are there any situations in which it is impossible, purely from a technical standpoint, to open source your code?

Essentially; a feature which when the code is made public, invalidates/reduces the functionality of that feature.

Some examples I can think of:

Cheating in Quake - once the game was released as open source, id had to release a closed-source 'wrapper' to validate client code in order to prevent cheating.

Reddit - while the majority of the source for social news site Reddit is available, their anti-spam mechanisms are not. If the spammers knew how they worked, they'd be easier to work around.

Both security related and both as a result of using implementations security experts would probably frown on (Quake: trusting the client, Reddit: security through obscurity). Whether there are feasible alternatives to these implementations is another matter altogether...

What other examples are there of this? Are there any that aren't security related? Are they all due to 'workarounds' in order to make our systems work with the technology we have?

答:
In general you can't release an open source project if:

it breaks a criminal law,

it breaks intellectual property law and and intellectual rights (such as protected by patents)

it contains copyrighted content

part of it it's not your own work and it conflicts with other licenses

it contains some sensitive data, but you can always encrypt it (e.g. using BlackBox)

Related:

At what point having computer generated file is illegal?

What topics are not allowed when publishing open access controversial books?

When is making a subtitle file for a commercial movie legal?


问:
Strategy pattern and "Is a" relationship
Imagine, I have class IAlgo which is an interface. I have derived from him and implemented his single method called matchCount in different implementations - AlgoA1, AlgoA2, AlgoA3, AlgoB1, AlgoB2.

```<code>class IAlgo
{
    virtual int matchCount(T1* p1, T2* p2) = 0;
}

class AlgoA1 : public IAlgo
{
    virtual int matchCount(T1* p1, T2* p2) override
    {
         // impl here
    }
}
</code>```

The difference between AlgoAN and AlgoBK is that category A is interested in all params of matchCount and category B is interested in only first param and the rest can be null - category B does not use them.

So as an encapsulated algorithm I am using them in Strategy pattern. After some time, the product owner says that he wants a new type of algorithms (AlgoC category) that adds a new parameter to matchCount method - say T3*. So we should go back and change the whole hierarchy of IAlgo and all subclass to have the following form:

```<code>    virtual int matchCount(T1* p1, T2* p2, T3* p3) = 0;
</code>```

This is a design problem and it seems that I had encapsulated algorithm to use it as a strategy, but it didn't work. How I have to solve this problem? Is my problem is the fact that AlgoA, AlgoB and AlgoC families are not related and they should not derive from IAlgo and they don't have "IS A" relationship? Should I have different interfaces IAlgoA, IAlgoB and IAlgoC for different families? Or all this is fine and I need some other solution?

答:
How about simplifying the call to virtual int matchCount() by removing all arguments, and instantiating each Strategy with the arguments of the matchCount method in your question. Then you inject the concrete strategy into your Context.

Here are some ways to use the strategies (I'm not sure how it works in your real problem because there are no details in your question):


问:
Issues deciding on approach to create object
I'm trying to decide what's the best approach to instantiate a particular class. Basically there are two use cases for it: instantiate it in order to save a new entry to the database and fetch an existing entry from the database (and maybe edit the fetched entry and save it back to the database).

The issue I'm having right now is that I can't decide which mechanism for instantiating that class and populating its fields to choose. Say I have this class

```<code>public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
}
</code>```

And here are the usecases. If you want to fetch a student for the database, the code looks something like:

```<code>Student student = MyLibrary.GetStudent(id);
</code>```

And if you want to create a new student and add it to the database:

```<code>Student student = new Student();
student.FirstName = "James";
student.LastName = "Jackson";
// etc
MyLibrary.CreateStudent(student);
</code>```

The massive issue with this approach is that all the setters are public and I absolutely do not want this. But at the same time I want the user to be able to populate most of the Student fields freely (maybe with the exception of Id.

I'm thinking the builder pattern could be employed in here. This way I can keep the setters private and force the user to create read-only students via the builders. However it then becomes really awkward if the user wants to update a field and save it to the database:

```<code>var student = MyLibrary.GetStudent(id);
var newStudent = new Student.Builder(id).FirstName("NewFirstName").LastName(student.LastName)...etc...Build();
MyLibrary.CreateStudent(newStudent);
</code>```

Basically my only issue with the builder approach is that the code can get quite awkward and tedious if you want to update an existing entry. Some of the classes I have can have around 10 fields and it's not great having to copy 9 of the fields and update one. But it may be much nicer than having a class with public setters.

What other options do I have?

答:
I think a nonpublic set for "user editable" properties is just making work for yourself.

I'd leave them public (for changeable properties, i.e. not Id) and then either use the DAO-style .Edit and .Update state change methods (where attempting to change before calling .Edit throws a runtime error), or simply always allow changes and supply .CommitChanges to store them, similar to .NET DataContext.

This also allows something like:

```<code>LoadStudent(s);
s.Name="Harry";
if(UserConfirmsChanges(s))
  s.CommitChanges();
</code>```

where the important bit I'm referring to is UserConfirmsChanges which can work with modified, but not saved, data simply.

If you really want something similar to the DAO way, but with compile-time read only properties before .Edit, you'll have to have different classes or otherwise duplicate code.

Body:
I think a nonpublic set for "user editable" properties is just making work for yourself.

I'd leave them public (for changeable properties, i.e. not Id) and then either use the DAO-style .Edit and .Update state change methods (where attempting to change before calling .Edit throws a runtime error), or simply always allow changes and supply .CommitChanges to store them, similar to .NET DataContext.

This also allows something like:

LoadStudent(s);
s.Name="Harry";
if(UserConfirmsChanges(s))
  s.CommitChanges();

where the important bit I'm referring to is UserConfirmsChanges which can work with modified, but not saved, data simply.

If you really want something similar to the DAO way, but with compile-time read only properties before .Edit, you'll have to have different classes or otherwise duplicate code.


答: Maybe I'm being pedantic, but "assembler" isn't a programming language, it is a piece of software for translating assembly instruction mnemonics into opcodes for a particular processor. If you want to say you know assembly language, list Assembly Language for XXX processor in your CV.


答:
How many times have you gotten that automated email saying your last commit broke the build? How many times is it wrong? But now you have to go check to see if it really was you, or someone else who did another commit around the same time. Or maybe it was something environmental. </p>

<p>If the system doesn't know for sure, then I certainly don't want to automate it. </p>

Body:
How many times have you gotten that automated email saying your last commit broke the build? How many times is it wrong? But now you have to go check to see if it really was you, or someone else who did another commit around the same time. Or maybe it was something environmental.

If the system doesn't know for sure, then I certainly don't want to automate it.


问:
How to calculate min/max values of floating point numbers?
I'm trying to calculate the min/max, or the lowest to highest value range of a 48 bit floating point type MIL-STD-1750A (PDF) (WIKI).

Ex: How a double range is 1.7E +/- 308

I've looked around for equations, and am unsure if what I have found will work.

The first equation I found was

The second was

I'm not quite sure where to begin with these, if they are even correct in what I need.

Will someone impart their knowledge to me and help solve this?

答:
You can borrow from how the IEEE floating point is laid out for fast comparison: sign, exponent, mantissa. however in that PDF I see mantissa and exponent are reversed.

This means that to compare you'll have to first check the sign bit and if one is not the winner yet you compare the exponents and then you compare the mantissa.

If one is positive and the other is negative then the positive is the max.

If both are positive and one exponent is larger then it is the max (if both are negative then it is the min)

Similarly for mantissa.


答:
We use Jenkins for our build server and use the gatekeeper model for pushing commits -- where a combination of Jenkins and commit triggers (that ensure peer reviewers have done their job) is the gatekeeper.

Commits are pushed indirectly through a curl to Jenkins, where it clones the master repo then pulls in the commit(s) to be merged and performs all required builds (for Linux/solaris).  If all builds complete, the commit gets pushed.

This avoids many if not all of the problems discussed so far:

history alteration

getting history correct if you're the dev who has to fix the breakage

instability (in the form of broken builds) is never introduced

It also allows us to directly enforce other requirements such as unit tests completing successfully.


问:
Can I use the Simple and Fast Multimedia Library (SFML) in a proprietary piece of software?
I have been asked to develop a small game for a conference. The game isn't anything big and since I have had previous experience with SFML, I figured it would be the easiest to use.

The SFML licensing page says that it may be used in proprietary software, however, it includes several other libraries that are licensed under BSD 3, LGPL and FTL.

I do not plan on changing the SFML source code, just use it.

答:
Just taking a quick look at those licenses (I don't remember hearing about FTL before today, but I may have), I don't see an issue.

To meet the terms of the BSD 3-clause license, all you need to do is to include the copyright and disclaimer with the distribution, and I'm assuming that the distributors of SFML have clearly identified which libraries or packages they are including and which ones are BSD. The BSD license is friendly to inclusion in closed-source projects:

Any BSD code can be sold or included in proprietary products without any restrictions on the availability of your code or your future behavior.

Section 4 Combined Works of the LGPL also covers your case. There are already some questions on Programmers specifically about using the LGPL in closed-source applications here and here.

It appears that the terms of using something licensed under FTL are very much like the BSD license. You do need to provide a disclaimer that your application is based on work of the FreeType team and they ask that you link to the FreeType webpage.

It looks like as you don't modify SFML and SFML either didn't modify the other libraries or complied with the license terms regarding modifications for the other libraries, you can indeed use SFML in a closed-source application.


答:
For 32-bit floating point, the maximum value is shown in Table III:

```<code>0.9999998 x 2^127 represented in hex as: mantissa=7FFFFF, exponent=7F.
</code>```

We can decompose the mantissa/exponent into a (close) decimal value as follows:

```<code>7FFFFF <base-16> = 8,388,607 <base-10>.
</code>```

There are 23 bits of significance, so we divide 8,388,607 by 2^23.

```<code>8,388,607 / 2^23 = 0.99999988079071044921875 (see Table III)
</code>```

as far as the exponent:

```<code>7F <base-16> = 127 <base-10>
</code>```

and now we multiply the mantissa by 2^127 (the exponent)

```<code>8,388,607 / 2^23 * 2^127 =
8,388,607 * 2^104 = 1.7014116317805962808001687976863 * 10^38
</code>```

This is the largest 32-bit floating point value because the largest mantissa is used and the largest exponent.

The 48-bit floating point adds 16 bits of lessor significance mantissa but leaves the exponent the same size.  Thus, the max value would be represented in hex as

```<code>mansissa=7FFFFFFFFF, exponent=7F.
</code>```

again, we can compute

```<code>7FFFFFFFFF <base-16> = 549,755,813,887 <base-10>
</code>```

the max exponent is still 127, but we need to divide by [23+16=39, so:] 2^39.
127-39=88, so just multiply by 2^88:

```<code>549,755,813,887 * 2^88 =
1.7014118346015974672186595864716 * 10^38
</code>```

This is the largest 48-bit floating point value because we used the largest possible mantissa and largest possible exponent.

So, the max values are:

```<code>1.7014116317805962808001687976863 * 10^38, for 32-bit, and,
1.7014118346015974672186595864716 * 10^38, for 48-bit
</code>```

The max value for 48-bit is just slightly larger than for 32-bit, which stands to reason since a few bits are added to the end of the mantissa.

(To be exact the maximum number for the 48-bit format can be expressed as a binary number that consists of 39 1's followed by 88 0's.)

(The smallest is just the negative of this value.  The closest to zero without being zero can also easily be computed as per above: use the smallest possible (positive) mantissa:0000001 and the smallest possible exponent: 80 in hex, or -128 in decimal)

FYI

Some floating point formats use an unrepresented hidden 1 bit in the mantissa (this allows for one extra bit of precision in the mantissa, as follows: the first binary digit of all numbers (except 0, or denormals, see below) is a 1, therefore we don't have to store that 1, and we have an extra bit of precision).  This particular format doesn't seem to do this.

Other floating point formats allow denormalized mantissa, which allows representing (positive) numbers smaller than smallest the exponent, by trading bits of precision for additional (negative) powers of 2.  This easy to support if it doesn't also support the hidden one bit, a bit harder if it does.

8,388,607 / 2^23 is the value you'd get with mantissa=0x7FFFFF and exponent=0x00.  It is not the single bit value but rather the value with a full mantissa and a neutral, or more specifically, a zero exponent.

The reason this value is not directly 8388607, and requires division (by 2^23 and hence is less than what you might expect) is that the implied radix point is in front of the mantissa, rather than after it.  So, think +/-.111111111111111111111 (a sign bit, followed by a radix point, followed by twenty-three 1-bits) for the mantissa and +/-111111111111 (no radix point here, just an integer, in this case, 127) for the exponent.

mantissa = 0x7FFFFF with exponent = 0x7F is the largest value which corresponds to 8388607 * 2 ^ 104, where the 104 comes from 127-23: again, subtracting 23 powers of two because the mantissa has the radix point at the beginning.  If the radix point were at the end, then the largest value (0x7FFFFF,0x7F) would indeed be 8,388,607 * 2 ^ 127.

Among others, there are possible ways we can consider a single bit value for the mantissa.  One is mantissa=0x400000, and the other is mantissa=0x000001.  without considering the radix point or the exponent, the former is 4,194,304, and the latter is 1.   With a zero exponent and considering the radix point, the former is 0.5 (decimal) and the latter is 0.00000011920928955078125.  With a maximum (or minimum) exponent, we can compute max and min single bit values.

(Note that the latter format where the mantissa has leading zeros would be considered denormalized in some number formats, and its normalized representation would be 0x400000 with an exponent of -23).

Title: How to calculate min/max values of floating point numbers?

Body:
I'm trying to calculate the min/max, or the lowest to highest value range of a 48 bit floating point type MIL-STD-1750A (PDF) (WIKI).

Ex: How a double range is 1.7E +/- 308

I've looked around for equations, and am unsure if what I have found will work.

The first equation I found was

The second was

I'm not quite sure where to begin with these, if they are even correct in what I need.

Will someone impart their knowledge to me and help solve this?

Body:
For 32-bit floating point, the maximum value is shown in Table III:

0.9999998 x 2^127 represented in hex as: mantissa=7FFFFF, exponent=7F.

We can decompose the mantissa/exponent into a (close) decimal value as follows:

7FFFFF <base-16> = 8,388,607 <base-10>.

There are 23 bits of significance, so we divide 8,388,607 by 2^23.

8,388,607 / 2^23 = 0.99999988079071044921875 (see Table III)

as far as the exponent:

7F <base-16> = 127 <base-10>

and now we multiply the mantissa by 2^127 (the exponent)

8,388,607 / 2^23 * 2^127 =
8,388,607 * 2^104 = 1.7014116317805962808001687976863 * 10^38

This is the largest 32-bit floating point value because the largest mantissa is used and the largest exponent.

The 48-bit floating point adds 16 bits of lessor significance mantissa but leaves the exponent the same size.  Thus, the max value would be represented in hex as

mansissa=7FFFFFFFFF, exponent=7F.

again, we can compute

7FFFFFFFFF <base-16> = 549,755,813,887 <base-10>

the max exponent is still 127, but we need to divide by [23+16=39, so:] 2^39.
127-39=88, so just multiply by 2^88:

549,755,813,887 * 2^88 =
1.7014118346015974672186595864716 * 10^38

This is the largest 48-bit floating point value because we used the largest possible mantissa and largest possible exponent.

So, the max values are:

1.7014116317805962808001687976863 * 10^38, for 32-bit, and,
1.7014118346015974672186595864716 * 10^38, for 48-bit

The max value for 48-bit is just slightly larger than for 32-bit, which stands to reason since a few bits are added to the end of the mantissa.

(To be exact the maximum number for the 48-bit format can be expressed as a binary number that consists of 39 1's followed by 88 0's.)

(The smallest is just the negative of this value.  The closest to zero without being zero can also easily be computed as per above: use the smallest possible (positive) mantissa:0000001 and the smallest possible exponent: 80 in hex, or -128 in decimal)

FYI

Some floating point formats use an unrepresented hidden 1 bit in the mantissa (this allows for one extra bit of precision in the mantissa, as follows: the first binary digit of all numbers (except 0, or denormals, see below) is a 1, therefore we don't have to store that 1, and we have an extra bit of precision).  This particular format doesn't seem to do this.

Other floating point formats allow denormalized mantissa, which allows representing (positive) numbers smaller than smallest the exponent, by trading bits of precision for additional (negative) powers of 2.  This easy to support if it doesn't also support the hidden one bit, a bit harder if it does.

8,388,607 / 2^23 is the value you'd get with mantissa=0x7FFFFF and exponent=0x00.  It is not the single bit value but rather the value with a full mantissa and a neutral, or more specifically, a zero exponent.

The reason this value is not directly 8388607, and requires division (by 2^23 and hence is less than what you might expect) is that the implied radix point is in front of the mantissa, rather than after it.  So, think +/-.111111111111111111111 (a sign bit, followed by a radix point, followed by twenty-three 1-bits) for the mantissa and +/-111111111111 (no radix point here, just an integer, in this case, 127) for the exponent.

mantissa = 0x7FFFFF with exponent = 0x7F is the largest value which corresponds to 8388607 * 2 ^ 104, where the 104 comes from 127-23: again, subtracting 23 powers of two because the mantissa has the radix point at the beginning.  If the radix point were at the end, then the largest value (0x7FFFFF,0x7F) would indeed be 8,388,607 * 2 ^ 127.

Among others, there are possible ways we can consider a single bit value for the mantissa.  One is mantissa=0x400000, and the other is mantissa=0x000001.  without considering the radix point or the exponent, the former is 4,194,304, and the latter is 1.   With a zero exponent and considering the radix point, the former is 0.5 (decimal) and the latter is 0.00000011920928955078125.  With a maximum (or minimum) exponent, we can compute max and min single bit values.

(Note that the latter format where the mantissa has leading zeros would be considered denormalized in some number formats, and its normalized representation would be 0x400000 with an exponent of -23).

ContentLicense: CC BY-SA 4.0


问:
Rest Client API design and implementation (with RestEasy)
I am working on a design to create a generic rest client for our application for current and future integration's with multiple services (different external systems). Following is a high level diagram

I am thinking of creating a RestClient per external host, and Store them in a Map with Service name as Key and RestClient as value. Following is my RestClient(will be cached) class that wraps ResteasyWebTarget.

```<code>public class RestClient {
    private ResteasyWebTarget target;

    @Singleton
    public class RestClientRepository {
        private final Map<String, RestClient> repository =
            new ConcurrentHashMap<String, RestClient>()
</code>```

My default implementation will be using RestEasy. As my client code will be part of a webapp(multihtreaded environment). I will be using PoolingClientConnectionManager

```<code>ClientConnectionManager cm = new PoolingClientConnectionManager();
HttpClient httpClient = new DefaultHttpClient(cm);
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
ResteasyClient client = ((ResteasyClientBuilder) ResteasyClientBuilder
  .newBuilder()).httpEngine(engine).build();
</code>```

Is there a better solution than this approach?

答:
In the first place it seems to be right, but I think you want to hide these implementation details. Ask your self: where is the difference between a local database and some remote data servers?

You probably want to have a been for each resource like User and a store like UserStore. Each store has some methods for interaction like:

```<code>public User getUser(String, String)
public User getUserById(long)
public void updateUser(User) throws ...
public void deleteUser(User)
public void createUser(User)
</code>```

This hides the implementation details of your REST API. And the details of caching locally and so on (if you want to cache locally you have to synchronize the data and doing synchronization correctly is very hard to solve!)

Body:
In the first place it seems to be right, but I think you want to hide these implementation details. Ask your self: where is the difference between a local database and some remote data servers?

You probably want to have a been for each resource like User and a store like UserStore. Each store has some methods for interaction like:

public User getUser(String, String)
public User getUserById(long)
public void updateUser(User) throws ...
public void deleteUser(User)
public void createUser(User)

This hides the implementation details of your REST API. And the details of caching locally and so on (if you want to cache locally you have to synchronize the data and doing synchronization correctly is very hard to solve!)


答:
My preferred method which I have been using for at least a few years now is to bump up the number after each story is completed. This means that the versions released at the end of the sprint will not be continuous, e.g. after 1.2.3 you might find 1.5.2 rather than 1.4.0.

In the changelog you may either list the intermediate versions with their corresponding descriptions or just group all changes into the "released" version and skip the versions in between.

Initially, I was afraid users would find the "holes" between version numbers problematic, but once they know about it, it is not an issue in practice. The big advantage is that increasing the number after each story makes the process less error prone - you don't have to check the whole work from 2 weeks to decide what next version number will be - when looking at a single story, it is obvious. Additionally, the "leaps" in version numbers between each release give a rough estimate of how many changes went into the release. All in all, I have found this system to work well (this was with company-internal customers, but if you already work in an agile release cycle it should work for external customers as well).

Title: Semantic versioning in Agile