问:
How can I work out how many IP addresses there are in a given range?
I'm wondering if there is a formula to work out the amount of IP addresses in a given range.

I have a system that takes either a single IP address or a start and and end IP address:

A single one might be: 145.16.23.241

A range might be: 145.16.23.122 - 145.16.23.144

The people inputting these aren't technical, nor are they receiving these details from technical people, so suggesting using CIDR notation isn't an answer for me.

I want to be able to highlight that when entering a range such as: 122.100.10.12 - 128.10.200.140 it might not actually be a range and rather 2 singular IP addresses since such a range would comprise of x (large number of) IP addresses.

Is there a basic formula to help me highlight this?

答:
Note that to properly convert dotted IP addresses to a 32-bit number and do mathy things on them reliably, you need to use an unsigned integer type. If the only integer types available to you are signed, then...

Another way to calculate it is this: starting with the first octet that is different, multiply each octet's difference from that point on by the following numbers, and then add these differences together:

```<code>1: 16777216
2: 65536
3: 256
4: 1
</code>```

For example, using your range 122.100.10.12 - 128.10.200.140:

```<code>  128  10   200  140
- 122  100   10   12
=   6 -90   190  128

= 16777216 * 6
+ 65536 * -90
+ 256 * 190
+ 1 * 128
= 94813824
</code>```

This is the same value you'd get doing the whole conversion of

```<code>0x800AC88C = 2148190348
0x7A640A0C = 2053376524
</code>```

and then subtracting.

Additionally, you can also perform the same operation this way:

```<code>((a[0] - b[0]) * 256 + a[1] - b[1]) * 256 + a[2] - b[2]) * 256 + a[3] - b[3]
</code>```

This is easily susceptible to a reduce that collapses each next pair of values repeatedly.

Body:
Note that to properly convert dotted IP addresses to a 32-bit number and do mathy things on them reliably, you need to use an unsigned integer type. If the only integer types available to you are signed, then...

Another way to calculate it is this: starting with the first octet that is different, multiply each octet's difference from that point on by the following numbers, and then add these differences together:

1: 16777216
2: 65536
3: 256
4: 1

For example, using your range 122.100.10.12 - 128.10.200.140:

  128  10   200  140
- 122  100   10   12
=   6 -90   190  128

= 16777216 * 6
+ 65536 * -90
+ 256 * 190
+ 1 * 128
= 94813824

This is the same value you'd get doing the whole conversion of

0x800AC88C = 2148190348
0x7A640A0C = 2053376524

and then subtracting.

Additionally, you can also perform the same operation this way:

((a[0] - b[0]) * 256 + a[1] - b[1]) * 256 + a[2] - b[2]) * 256 + a[3] - b[3]

This is easily susceptible to a reduce that collapses each next pair of values repeatedly.


答:
You have to be clear how you are defining these ranges. Maybe you meant all of the addresses whose 32-bit representations fall between the two numbers, and that's what the other answers here seem to assume. So for example, 1.0.0.0 - 1.0.2.0 includes all of the following IP addresses:

```<code>1.0.0.0 - 1.0.0.255
1.0.1.0 - 1.0.1.255
1.0.2.0
</code>```

However, when I first read your question, what I thought you meant was defining separate ranges for each byte, in which case the range 1.0.0.0 - 1.0.2.0 would mean only the following three addresses:

```<code>1.0.0.0
1.0.1.0
1.0.2.0
</code>```

For the first case, as others stated the correct answer is

```<code>abs(ip2-ip1)+1
</code>```

But in the second case, the correct answer would be

```<code>product(abs(ip2[i] - ip1[i]) + 1)
</code>```

where [i] means the ith byte of that IP, and the product is taken over the four bytes.

Make sure it's clear to your users which of these you mean.

ContentLicense: CC BY-SA 3.0

Title: How can I work out how many IP addresses there are in a given range?

Body:
I'm wondering if there is a formula to work out the amount of IP addresses in a given range.

I have a system that takes either a single IP address or a start and and end IP address:

A single one might be: 145.16.23.241

A range might be: 145.16.23.122 - 145.16.23.144

The people inputting these aren't technical, nor are they receiving these details from technical people, so suggesting using CIDR notation isn't an answer for me.

I want to be able to highlight that when entering a range such as: 122.100.10.12 - 128.10.200.140 it might not actually be a range and rather 2 singular IP addresses since such a range would comprise of x (large number of) IP addresses.

Is there a basic formula to help me highlight this?

Body:
You have to be clear how you are defining these ranges. Maybe you meant all of the addresses whose 32-bit representations fall between the two numbers, and that's what the other answers here seem to assume. So for example, 1.0.0.0 - 1.0.2.0 includes all of the following IP addresses:

1.0.0.0 - 1.0.0.255
1.0.1.0 - 1.0.1.255
1.0.2.0

However, when I first read your question, what I thought you meant was defining separate ranges for each byte, in which case the range 1.0.0.0 - 1.0.2.0 would mean only the following three addresses:

1.0.0.0
1.0.1.0
1.0.2.0

For the first case, as others stated the correct answer is

abs(ip2-ip1)+1

But in the second case, the correct answer would be

product(abs(ip2[i] - ip1[i]) + 1)

where [i] means the ith byte of that IP, and the product is taken over the four bytes.

Make sure it's clear to your users which of these you mean.


问:
Are short identifiers bad?
Are short identifiers bad? How does identifier length correlate with code comprehension? What other factors (besides code comprehension) might be of consideration when it comes to naming identifiers?

Just to try to keep the quality of the answers up, please note that there is some research on the subject already!

Edit

Curious that everyone either doesn't think length is relevant or tend to prefer larger identifiers, when both links I provided indicate large identifiers are harmful!

Broken Link

The link below pointed to a research on the subject, but it's now broken, I don't seem to have a copy of the paper with me, and I don't recall what it was. I'm leaving it here in case someone else figure it out.

http://evergreen.loyola.edu/chm/www/Papers/SCP2009.pdf

答: On the contrary, I think long identifiers are worse than short identifiers (unless you're dealing with constants).  Using TheVariableThatHoldsTheCapacityOfMyContainerClass makes your code a lot more prone to errors than using Capacity.

Title: Are short identifiers bad?

ContentLicense: CC BY-SA 2.5


问:
Is is OK to use a non-primary key as the id in a rails resource?
I am getting ready to set up a resource for some new api calls to my rails application.

I am planning on calling the resource devices ie

```<code>resources :devices
</code>```

This is going to represent android mobile devices

I know this will get me routes such as

GET devices/:id

In most cases :id would be an integer representing the primary key, and in the controller we would use :id as such:

```<code>GET devices/1
@device = Device.find(params[:id])
</code>```

In this case I would like to use :id as the google_cloud_messaging_reg_id

So I would like to have requests like this:

```<code>GET devices/some_long_gcm_id
</code>```

and then in the controller , just us params[:id] to look up the device by the gcm registration id.  This seem more natural, since the device will know it's gcm id rather than it's rails integer id.  Are there any reasons I should avoid doing this?

---------------------------------------------------------------------

UPDATE:

My initial concern was that seeing a route (via rake routes) of /devices/:id or looking at the controller and seeing params[:id] would be confusing since most would assume :id was the integer primary key.

After  thinking about it some more, and reading Idan Arye's answer below, my current thinking is to create routes like shown below.  This will get me routes (via rake routes) that look like this:

```<code>GET    /api/v1/android_devices/:gcm_reg_key(.:format)
</code>```

which I think makes it somewhat clear that :gcm_reg_key may not be a primary key integer.
And in the controller the parameter would be

```<code>params[:gcm_reg_key]
</code>```

Again, I think this makes it somewhat clear that the param may not be an integer primary key (convention would be params[:id])

Any other thoughts or suggestions are welcome.

```<code>match '/android_devices/:gcm_reg_key', to: 'android_devices#show' , via: :get, as: 'android_device'
match '/android_devices/:gcm_reg_key', to: 'android_devices#update', via: :post, as: 'android_device_create'
match '/android_devices/:gcm_reg_key', to: 'android_devices#update', via: :patch, as: 'android_device_modify'
match '/android_devices/:gcm_reg_key', to: 'android_devices#destroy', via: :delete, as: 'android_device_destroy'
resources :android_devices , only: [:create, :index]
</code>```

答:
Actually, there are 3 reasons:

Convention

Convention

Convention

Convention is important, because it makes it easier for other programmers to understand your code. In RoR it's even more important, since many facilities of the framework and 3rd party plugins are assuming you are following the convention. Often they'll offer a configuration interface you can use in case you violate the convention, but this will make their usage more verbose, complicated, and error-prone.

So, you should only break convention if you have a really good reason to do so - and this isn't one, because there is a much simpler alternative: using the GET parameters!

Instead of hijacking the show action, create a new route - e.g. find_and_show. That action will accept the GCM id as a GET parameter instead as part of the path, so the path will be:

```<code>GET devices/find_and_show?gcm_id=<some_long_gcm_id>
</code>```

The method should find the Device by the gcm_id, and the rest of it could be shared with the regular show method, or even delegated to it with a redirect.

This way you are not breaking any convention, you are making it clear that you are searching by GCM id rather than by the PK, and if you ever want to allow retrieving via other unique identifiers you can simply make find_and_show support more GET parameters.

And yes, it'll make the URLs longer, but it's not like humans will type these URLs...

OwnerDisplayName: nPn

Body:
Actually, there are 3 reasons:

Convention

Convention

Convention

Convention is important, because it makes it easier for other programmers to understand your code. In RoR it's even more important, since many facilities of the framework and 3rd party plugins are assuming you are following the convention. Often they'll offer a configuration interface you can use in case you violate the convention, but this will make their usage more verbose, complicated, and error-prone.

So, you should only break convention if you have a really good reason to do so - and this isn't one, because there is a much simpler alternative: using the GET parameters!

Instead of hijacking the show action, create a new route - e.g. find_and_show. That action will accept the GCM id as a GET parameter instead as part of the path, so the path will be:

GET devices/find_and_show?gcm_id=<some_long_gcm_id>

The method should find the Device by the gcm_id, and the rest of it could be shared with the regular show method, or even delegated to it with a redirect.

This way you are not breaking any convention, you are making it clear that you are searching by GCM id rather than by the PK, and if you ever want to allow retrieving via other unique identifiers you can simply make find_and_show support more GET parameters.

And yes, it'll make the URLs longer, but it's not like humans will type these URLs...


问:
Jasmine BDD vs Integration Tests
Let's say I need to write a test for the front end, in the following BDD style:

```<code>A user visits buysomething.com,
saves something to their wishlist,
and a saved item count is updated.
</code>```

The result of the test is that DOM gets manipulated.

In my heart I feel this is better suited as an integration test - but my team is currently using jasmine to load fixtures and test such interactions. This can lead to brittle tests as they are reliant on a static fixtures instead of the actual markup.

Are we misusing Jasmine here?

答:
Do both. Integration tests serve the purpose of checking that two pieces of functionality that should work together do work together. BDD (or any other form of acceptance) tests verify that the user-visible feature works according to the needs of the customer and the business. If the end requirement is that someone can access a website, you must do that with a non-integration test because that's how the user will interact with the system.

All that being said, don't get hung up on terminology. Call the tests whatever you want. At the end of the day the software needs to be tested. You don't get bonus points for testing them with BDD or with functional or unit tests. The only bonus points are whether or not the software is as bug-free as possible.

In a perfect world you would have a huge pile of unit tests that test each unit individually, a smaller set of integration tests that verify the integration of each of those units, and an even smaller set that verifies that the UI is functioning properly and calls the appropriate functions. And, of course, an even smaller set of exploratory tests that let your trained quality analysts use their intuition to find the really deep, gnarly bugs that are hard to catch in an automated fashion.

Title: Jasmine BDD vs Integration Tests


问:
"Default approach" when creating a class from scratch: getters for everything, or limited access?
Until recently I always had getters (and sometimes setters but not always) for all the fields in my class. It was my 'default': very automatic and I never doubted it. However recently some discussions on this site made me realize maybe it's not the best approach.

When you create a class, you often don't know exactly how it's going to be used in the future by other classes.

So in that sense, it's good to have getters and setter for all of the fields in the class. So other classes could use it in the future any way they want. Allowing this flexibility doesn't require you to over engineer anything, only to provide getters.

However some would say it's better to limit the access to a class, and only allow access to certain fields, while other fields stay completely private.

What is your 'default' approach when building a class from scratch? Do you make getters for all the fields? Or do you always choose selectively which fields to expose through a getter and which to keep completely private?

答:
Expose properties and methods that are going to be part of the public API of the class, or which fulfill an interface contract.

You should be thinking about your class's API from the start, not based on what you intend to expose publicly, but instead what functionality your class is going to provide.


问:
What interface does python use to implement sockets?
When I programmed in python, I believe I interfaced with the transport layer using sockets.  If python was programmed by humans, they must have used an interface that was "lower" than sockets, to provide us with the interface to sockets.  I assume firewalls, also programmed by humans, use interfaces of lower layers in the same manner, so is there a way to access such lower layers, in terms of programming?

答:
To give some detail, here is Python's implementation of the socket() call.  That is, the following code is called when you do x=socket.socket() in Python, which initializes a _socketobject object for you.  It shows that in CPython, eventually it calls the good old C socket() function.

http://hg.python.org/cpython/file/57130574d1e8/Modules/socketmodule.c#l3995


问:
Flags with deferred use
Let's say I have a system. In this system I have a number of operations I can do, but all of these operations have to happen as a batch at a certain time, while calls to activate and deactivate these operations can come in at any time. No matter how many times the doOperation1() method/function is called the operation is done only once in the batch. To implement this, I could use flags like doOperation1 and doOperation2 but this seems like it would become difficult to maintain. Is there a design pattern, or something similar, that addresses this situation?

答:
```<code>class A {
    void foo() { ... }
}

class DoFooOnce {
    bool activated = false;

    void activateFoo (A obj) {
        if (!activated) {
            activated = true;
            obj.foo();
        }
  }
}

main () {
    A obj1;
    B obj2;
    C obj3;

    DoFooOnce guard;

    guard.activateFoo(obj1);
    guard.activateFoo(obj2);
    guard.activateFoo(obj3);
}
</code>```

Title: Flags with deferred use


问:
Image caching when rendering the same images on different pages
I'm told to think about caching of images that will be displayed on the page. The images will be repeated throughout the website on different pages and I'm told to figure out the best way to cache these images. There could be few to dozen of images on single page.

Here's few questions:

Will browser caching work to display the same images across different web pages?

Should I rather store images in stringified form in a memory instead, using JavaScript arrays?

Store them on hard drive using 'localStorage'?

What would be easiest yet best option for this?

Are there any other alternatives?

How to force cache?

Any other information would be greatly appreciated...

答:
Images are cached by the browser in both an in-memory cache (that lasts no longer than the duration of a browser session) and a disk-based cache (that can last across sessions according to the disk cache settings - size and duration) as long as the server doesn't explicitly prevent the images from being cached based on settings in the http headers.

A given image is cached once, no matter what page it is used on and, as long as the URL is the same everywhere, the same cached copy will be used on all pages that specify that image until the image ages out of the cache or the cache is cleared or the browser decides that the cached copy may be stale.

There should be little reason to re-invent image caching by doing your own.

If you have lots of small images in your page, then a common speed improvement is to combine multiple images into a sprite and display each one as a different portion of the sprite.


答:
I tend to follow Robert Harvey's answer (focus on the functionality of the class, not the bits to do that), but there's some more to it than that.

It is rare that you're ever making one class from scratch. You're often providing some set of functionality, and a key decision to make is where to draw the lines to break that set of functionality into class-sized chunks. What's a class sized chunk? A single responsibility.

Personally, I find it effective to draw those lines of separation so that the individual classes provide a good API, but also differ in how mutable they are. Especially as programs become more concurrent and more complex, immutable objects allow your implementation to be simpler, more robust and more bugfree.

So in reference to the question, "by default" I aim to make my classes immutable when possible. They take what they need in the constructor and expose the functionality that is that class' responsibility. After that, I aim to make mutable objects have a default constructor and a sane initial state.

Once I'm on to mutable objects it depends on what the object does. Some objects are a set of functionality where the user can manipulate a state, but not necessarily data. Think of the progression of a game of poker. The poker game here is mutable because its state can progress. For these objects, "by default" I will go with conventional encapsulation. The state (who has what cards, who is the dealer, what the pot is) is hidden and the functionality (deal cards, bet, raise, etc.) is exposed.

Some objects are just data. Think of a contact in your email app. Here, the purpose of the object is just to bundle the name, email address, phone number, etc. together so the user can edit them. Having that publically mutable data is the responsibility of the object, so just make the stuff public. Languages with properties make this easier, but there should be little functionality in these sorts of classes (again, "by default").

Title: "Default approach" when creating a class from scratch: getters for everything, or limited access?

Body:
Until recently I always had getters (and sometimes setters but not always) for all the fields in my class. It was my 'default': very automatic and I never doubted it. However recently some discussions on this site made me realize maybe it's not the best approach.

When you create a class, you often don't know exactly how it's going to be used in the future by other classes.

So in that sense, it's good to have getters and setter for all of the fields in the class. So other classes could use it in the future any way they want. Allowing this flexibility doesn't require you to over engineer anything, only to provide getters.

However some would say it's better to limit the access to a class, and only allow access to certain fields, while other fields stay completely private.

What is your 'default' approach when building a class from scratch? Do you make getters for all the fields? Or do you always choose selectively which fields to expose through a getter and which to keep completely private?


答:
That really depends on the purpose of the class. If it's a "struct" class that just bundles data together, then it should expose all of its fields since it only keeps them, not using them. Classes that have actual behavior should usually be more restrictive in providing access to their inner state.

Always exposing the internal structure "So other classes could use it in the future any way they want" violates the very core of OOP. The class should be the one who defines how to use its internal structure, and provide an interface (methods) for doing so.

Take for example a C++ array-with-length (I haven't written C++ in a long time, so forgive any syntax errors):

```<code>class Array{
    private:
        int* array;
        size_t length;
    public:
        Array(size_t length):length(length){
            array=new int[length];
        }

        size_t getLength(){
            return length;
        }
        void setLength(size_t length){
            this.length=length;
        }

        int* getArray(){
            return array;
        }
        void setArray(int* array){
            this.array=array;
        }
}
</code>```

This class is so wrong that this answer might get flagged as offensive. It exposes the internal state - array and length - so other classes will be able to use my class any way they want. For example, if some code somewhere else wants to set the length to be different than the amount of memory (times sizeof(int)) allocated to array, they'll be able to do it!

My class shouldn't let others play freely with its internal state. Instead, it should provide an interface for modifying that state in a way that keeps it stable.

Body:
That really depends on the purpose of the class. If it's a "struct" class that just bundles data together, then it should expose all of its fields since it only keeps them, not using them. Classes that have actual behavior should usually be more restrictive in providing access to their inner state.

Always exposing the internal structure "So other classes could use it in the future any way they want" violates the very core of OOP. The class should be the one who defines how to use its internal structure, and provide an interface (methods) for doing so.

Take for example a C++ array-with-length (I haven't written C++ in a long time, so forgive any syntax errors):

class Array{
    private:
        int* array;
        size_t length;
    public:
        Array(size_t length):length(length){
            array=new int[length];
        }

        size_t getLength(){
            return length;
        }
        void setLength(size_t length){
            this.length=length;
        }

        int* getArray(){
            return array;
        }
        void setArray(int* array){
            this.array=array;
        }
}

This class is so wrong that this answer might get flagged as offensive. It exposes the internal state - array and length - so other classes will be able to use my class any way they want. For example, if some code somewhere else wants to set the length to be different than the amount of memory (times sizeof(int)) allocated to array, they'll be able to do it!

My class shouldn't let others play freely with its internal state. Instead, it should provide an interface for modifying that state in a way that keeps it stable.


问:
"Collection Wrapper" pattern - is this common?
A different question of mine had to do with encapsulating member data structures inside classes. In order to understand this question better please read that question and look at the approach discussed.

One of the guys who answered that question said that the approach is good, but if I understood him correctly - he said that there should be a class existing just for the purpose of wrapping the collection, instead of an ordinary class offering a number of public methods just to access the member collection.

For example, instead of this:

```<code>class SomeClass{

    // downright exposing the concrete collection.

    Things[] someCollection;

   // other stuff omitted

    Thing[] getCollection(){return someCollection;}

}
</code>```

Or this:

```<code>class SomeClass{

    // encapsulating the collection, but inflating the class' public interface.

    Thing[] someCollection;

    // class functionality omitted.

    public Thing getThing(int index){
        return someCollection[index];
    }

    public int getSize(){
        return someCollection.length;
    }

    public void setThing(int index, Thing thing){
        someCollection[index] = thing;
    }

    public void removeThing(int index){
        someCollection[index] = null;
    }

}
</code>```

We'll have this:

```<code>// encapsulating the collection - in a different class, dedicated to this.

class SomeClass{
    CollectionWrapper someCollection;

    CollectionWrapper  getCollection(){return someCollection;}
}

class CollectionWrapper{

    Thing[] someCollection;

    public Thing getThing(int index){
        return someCollection[index];
    }

    public int getSize(){
        return someCollection.length;
    }

    public void setThing(int index, Thing thing){
        someCollection[index] = thing;
    }

    public void removeThing(int index){
        someCollection[index] = null;
    }

}
</code>```

This way, the inner data structure in SomeClass can change without affecting client code, and without forcing SomeClass to offer a lot of public methods just to access the inner collection. CollectionWrapper does this instead.

E.g. if the collection changes from an array to a List, the internal implementation of CollectionWrapper changes, but client code stays the same.

Also, the CollectionWrapper can hide certain things from the client code - from example, it can disallow mutation to the collection by not having the methods setThing and removeThing.

This approach to decoupling client code from the concrete data structure seems IMHO pretty good.

Is this approach common? What are it's downfalls? Is this used in practice?

答:
You said,

What I'm trying to do, is not expose the collection - because I don't want the client code to break when the collection changes say from a List to a Set.

I have concerns about that requirement -- whether perceived or real.

The abstractions represented by those standard containers are so distinct and different, I find it hard that you will be able to substitute one for another in your interface. If SomeClass provides an interface that is more appropriate for a Set, you have to honor that interface regardless of how you implement the Set. The same logic applies for List too. In that sense, you don't have to expose ContainerWrapper or Container at all. They are implementation details of SomeClass. You could use pimpl pattern to completely hide the container.

Perhaps SomeClass is a container of objects with additional meaning.

For example, in a CAD program, an Assembly consists of sub-components that can be Parts or sub-Assemblies. However, that is not sufficient to capture the relationship between an Assembly and one of its sub-components. The location and orientation of the sub-component in the Assembly is the key piece of data that makes this particular container-contained relationship work. For this case, whether you store the collection of Pair as a List or a Set is of very little importance in the interface of Assembly. You need to be able to query the Assembly for its sub-components and given a sub-component, you need to be able to query the Assembly for the transform of the sub-component in the Assembly.

Another example: A Canvas and its contained objects in a 2D painting program or an SVG program. Here again, the container-contained relationship has to be created using the 2D position of the contained objects plus a depth to
in order to arrange them in layers. Here also, you can use a Set or a List to hold the contained objects.

In conclusion, I am asking you to dig deeper to determine the kind of relationship SomeClass has with its contained objects. Is it a matter of simple containment or is there more to the relationship? If there is more to the relationship, how would you expose the relationship that is divorced from a List or a Set.

In both the examples I presented, a List makes more sense to me. I can't say what makes more sense for SomeClass.

Body:
You said,

What I'm trying to do, is not expose the collection - because I don't want the client code to break when the collection changes say from a List to a Set.

I have concerns about that requirement -- whether perceived or real.

The abstractions represented by those standard containers are so distinct and different, I find it hard that you will be able to substitute one for another in your interface. If SomeClass provides an interface that is more appropriate for a Set, you have to honor that interface regardless of how you implement the Set. The same logic applies for List too. In that sense, you don't have to expose ContainerWrapper or Container at all. They are implementation details of SomeClass. You could use pimpl pattern to completely hide the container.

Perhaps SomeClass is a container of objects with additional meaning.

For example, in a CAD program, an Assembly consists of sub-components that can be Parts or sub-Assemblies. However, that is not sufficient to capture the relationship between an Assembly and one of its sub-components. The location and orientation of the sub-component in the Assembly is the key piece of data that makes this particular container-contained relationship work. For this case, whether you store the collection of Pair<sub-component, transform> as a List or a Set is of very little importance in the interface of Assembly. You need to be able to query the Assembly for its sub-components and given a sub-component, you need to be able to query the Assembly for the transform of the sub-component in the Assembly.

Another example: A Canvas and its contained objects in a 2D painting program or an SVG program. Here again, the container-contained relationship has to be created using the 2D position of the contained objects plus a depth to
in order to arrange them in layers. Here also, you can use a Set or a List to hold the contained objects.

In conclusion, I am asking you to dig deeper to determine the kind of relationship SomeClass has with its contained objects. Is it a matter of simple containment or is there more to the relationship? If there is more to the relationship, how would you expose the relationship that is divorced from a List or a Set.

In both the examples I presented, a List makes more sense to me. I can't say what makes more sense for SomeClass.


问:
Which is more expensive multiple conditional branches or multiple relational expression in a single condition?
Which is more expensive in terms of processing costs

```<code>if ( x < 20 && z == "M") {
    // statements 3
}

if ( x >= 20 && w && x <= 65) {
    // statements 1
}

if( x >= 20 && z == "F"){
    // statements 2
}
</code>```

or this

```<code>if ( x < 20 ) {
    if( z == 'M') // statements 3;
} else
    if ( x <= 65 && w == true ) // statements 1;
    if ( z == 'F' ) // statements 2;
}
</code>```

答:
Assuming you are doing this in C or C++, and assuming a production-quality compiler:

If x was declared "volatile", the first will be slightly more expensive, and the second may yield incorrect results.

If x was not declared "volatile", and optimization is on, they should yield identical code.


问:
How do you react to non-programmers with ideas of 'The Next Big Thing'?
Recently and quite often, people with no programming background come and say they have this great idea that can be the next big thing and that the idea(s) is worth a fortune by itself. Then as they know I'm a programmer, they ask me if I'm willing to "code it up" for them or find someone willing to do it for next to nothing.

Judging from the enthusiasm, it's like they're drunk on their idea and that that by itself is the most important thing, but they just need a programmer. My response to them, depending on my mood and their general attitude towards what we do, is something along the lines of:

"Having the core of an idea is one thing. Developing it to the point that it becomes a platform that changes the world in which it lives is another, and you're going to be willing to pay proportionately to how big you think your idea is worth."

Have you been approached by these business type entrepreneurs (with no technical/developer's knowledge) with such a proposal and how do you react to them?

答:
In my humble experience, it's the best to ask for a predictable payment then to expect an unpredictable win.
Even if in the long run you would like equity instead of fixed payment, this is a great way of filtering out people who are fakes. If you push the real buttons, you might even get them to say something like "Why are all of you programmers like that" (= he tried and failed, to fool a number of people).</p>


答:
Profile them

....then you'll see which is most expensive.

In all seriousness, the answer you're looking for depended on many, many factors such as language (your example could be any if several languages), compiler, compiler settings, platform and runtime use.

If you only ever call this code a handful of times, the performance is irrelevant compared to the maintainability - go for easy-to-maintain version.

Title: Which is more expensive multiple conditional branches or multiple relational expression in a single condition?

Body:
Which is more expensive in terms of processing costs

```<code>if ( x < 20 && z == "M") {
    // statements 3
}

if ( x >= 20 && w && x <= 65) {
    // statements 1
}

if( x >= 20 && z == "F"){
    // statements 2
}
</code>```

or this

```<code>if ( x < 20 ) {
    if( z == 'M') // statements 3;
} else
    if ( x <= 65 && w == true ) // statements 1;
    if ( z == 'F' ) // statements 2;
}
</code>```


问:
What are the most appropriate algorithms for downscaling images extremely while maintaining recognition?
I want to create a window icon (128x128 at most, the icon in the corner of the window on Windows is 24x24, I believe) from a large image (1024x768 and more). I've tried several algorithms - nearest neighbor, bicubic interpolation, but they all produce a very soft and barely recognizable image.

Do I need content-aware resize for this task?

答:
Generally when you want to make an icon in multiple sizes, you start with vector graphics which will allow you to resize without losing any information.  From there, you can resize it to the size of the icon and make the icon.  This is ideal.  Resizing from existing images is problematic since, unless it is a precise reduction in size (1/2x 1/4x 1/8x, etc.), pixels are going to have to be approximated even by the best algorithms.

If you have the original image, there are ways of "tracing" the image to be drawn as a svg file in Inkscape.  You lose a little bit of definition, but you can also make adjustments until it is closer to what you started with.  Once you have that, it is much easier to switch from svg format to other formats.

Hope that helps!


答:
You're describing the Encapsulated Collection pattern. I like this pattern a lot; it's especially appropriate to domain-driven design.

The advantage you describe - being able to change the internal representation of the collection - is a good one. But I think the bigger advantage is restricting clients' ability to modify or break the underlying collection.

For example, consider a "commenting" feature of a social network, with the requirement that you can't delete comments after they've been posted. If you expose the List<Comment> as a property, it's easy for clients of your class to call the list's Remove method without realising they weren't supposed to.

If, instead, you use a Comments class with a private List<Comment> and no Remove method, it's now impossible to break the invariant.

You also end up with a richer domain model, which is better equipped to deal with new features. (A collection of domain objects is often a new domain concept that your model is missing.) Imagine that the requirement's changed and now it's possible to delete comments, but the deletion has to be recorded in an audit trail. It's easy to implement this behaviour in a new Delete method on your Comments class - it would have been much more complicated to override the pre-existing Remove method on the List.

Title: "Collection Wrapper" pattern - is this common?

Body:
A different question of mine had to do with encapsulating member data structures inside classes. In order to understand this question better please read that question and look at the approach discussed.

One of the guys who answered that question said that the approach is good, but if I understood him correctly - he said that there should be a class existing just for the purpose of wrapping the collection, instead of an ordinary class offering a number of public methods just to access the member collection.

For example, instead of this:

```<code>class SomeClass{

    // downright exposing the concrete collection.

    Things[] someCollection;

   // other stuff omitted

    Thing[] getCollection(){return someCollection;}

}
</code>```

Or this:

```<code>class SomeClass{

    // encapsulating the collection, but inflating the class' public interface.

    Thing[] someCollection;

    // class functionality omitted.

    public Thing getThing(int index){
        return someCollection[index];
    }

    public int getSize(){
        return someCollection.length;
    }

    public void setThing(int index, Thing thing){
        someCollection[index] = thing;
    }

    public void removeThing(int index){
        someCollection[index] = null;
    }

}
</code>```

We'll have this:

```<code>// encapsulating the collection - in a different class, dedicated to this.

class SomeClass{
    CollectionWrapper someCollection;

    CollectionWrapper  getCollection(){return someCollection;}
}

class CollectionWrapper{

    Thing[] someCollection;

    public Thing getThing(int index){
        return someCollection[index];
    }

    public int getSize(){
        return someCollection.length;
    }

    public void setThing(int index, Thing thing){
        someCollection[index] = thing;
    }

    public void removeThing(int index){
        someCollection[index] = null;
    }

}
</code>```

This way, the inner data structure in SomeClass can change without affecting client code, and without forcing SomeClass to offer a lot of public methods just to access the inner collection. CollectionWrapper does this instead.

E.g. if the collection changes from an array to a List, the internal implementation of CollectionWrapper changes, but client code stays the same.

Also, the CollectionWrapper can hide certain things from the client code - from example, it can disallow mutation to the collection by not having the methods setThing and removeThing.

This approach to decoupling client code from the concrete data structure seems IMHO pretty good.

Is this approach common? What are it's downfalls? Is this used in practice?


答:
Most modern browsers are smart enough to cache images, atleast throughout a browser session. Here are a few ways you could use to optimize performance of repetitive images in your website.

You can tell the browser to cache the images for a long time by providing the appropriate HTTP header information, especially the Expires and Cache-control: max-age. Google developers has a nice best practices documentation for the same.

You can use Data URIs instead of actual image files. This reduces the extra HTTP request network overhead since the image data is actually part of the HTML page. You can use localStorage to save these Data URIs across browser sessions.

If you have many small images, you should consider using images with CSS sprites.

Title: Image caching when rendering the same images on different pages

Body:
I'm told to think about caching of images that will be displayed on the page. The images will be repeated throughout the website on different pages and I'm told to figure out the best way to cache these images. There could be few to dozen of images on single page.

Here's few questions:

Will browser caching work to display the same images across different web pages?

Should I rather store images in stringified form in a memory instead, using JavaScript arrays?

Store them on hard drive using 'localStorage'?

What would be easiest yet best option for this?

Are there any other alternatives?

How to force cache?

Any other information would be greatly appreciated...


问:
Being a good mentee - a protégé
The complement of the Being a good mentor question.

I work with many very senior people that have vast amounts of knowledge and wisdom in Software, Engineering and our business domain.

What are some tips for gaining as much knowledge from them?  I don't want to take up too much of their time, but also want to take full advantage of this since it really could help develop my skills.

What are some good questions to get the conversation rolling in a sit down mentor/mentee session?  Some of the people providing mentorship have little experience in this area, so it would help to be able to lead some of these discussions.

答:
Warning:  While this may sound like a smart alec answer and does have some humor, there is a legitimate point in this.

Do you just want to know more stuff or do you want to improve some technical skills?  There is a difference here as I'm sure everyone has a lot of personal trivia that has questionable value in the grand scheme of things.  If you want to develop your skills you will likely have to be willing to do a few things:

Assess yourself or handle feedback of an assessment - This is about knowing where you are, which can either be something you figure out yourself or have someone help you get there.  A key point here is to get to know where you are and why it may be both good and bad to be at this point.

Attempt to determine which skills need work - While this may be seen as a finding your weakness, I'd be more tempted to paint this as you want to have basic competency in some areas and this is just ensuring that.  Another way to see this is what areas do you want to improve and get better.  Finding your focus may be another way to see this.

Know how you learn and pick up stuff - Do you prefer to learn independently or as part of a group?  Do you prefer to read stuff or listen to it?  The key here is about knowing what learning style works for you which can take some trial and error.  What kinds of methods make sense to use between interactions to try to get better before getting assessed again.

Feedback on what's working and what's not - This is last on the list as this is more of a what to do a few months after you start to see if things are working our or not.  This can be the trickiest point as the key here is to see where you are better and what may not have worked as well as you'd hoped.  The flip side is to consider how well can you communicate these points as well as receive them since the relationship does have at least a couple of sides to it.  Did you pick up the new material?  If something was missed, how important was that piece?

Personality differences - Does the senior person tend to joke a lot more than you like?  Do they be overly serious in your view?  There are many relationship dynamics that can make those initial interactions annoying but there is a fine line between being assertive and stating what you feel and ramming it down the other person's throat,e.g. picture the "I will not be ignored" line from "Fatal Attraction" if you want a visual on this point.

Most of the questions above are rhetorical, but tend to highlight how to see if something is working for you or not.  The initial rules of the relationship shouldn't be that complicated at first though there is the acknowledging on each side that both of you want to be in this relationship and here is the focus for the next month or so.  I'd expect the first few months to be the hardest as this is where all kinds of crazy stuff will happen that after you get into that rhythm it may be surprising how comfortable some of it becomes.

Title: Being a good mentee - a protégé


问:
Algorithm to match timestamped events from two sources
I have two different physical devices (one is camera, one is other device) that observe the same scene and mark when a specified event occures. (record timestamp)

So they each produce a serie of timestamps "when the event was observed". Theoretically the recorded timestamps should be very well aligned:

Visualized ideal situation on two time lines "s" and "r" as recorded from the two devices:

but more likely they will not be so nicely aligned and there might be missing events from timeline s or r:

I am looking for algorithm to match events from "s" and "r" like this:

So that the result will be something like:
(s1,null); (s2,r1); (s3,null); (s4,r2); (s5,r3); (null,r4); (s6,r5);
Or something similar.
Maybe with some "confidence" rating.

I have some ideas, but I feel that this might be probably a well known problem, that has some good known solutions, but I don't know the right terminology. I am a little bit out of my element here, this is not my primary area of programming.. Any helps, suggestions etc will be appreciated.

答:
Here is my solution in C#, works good enough for my purposes:

```<code>///compute reasonably aligned pairs
        var max_tolerable_offset = 500; //do not match more then 500 miliseconds distant timestamps

        Dictionary<long, long> alignedPairs = new Dictionary<long, long>();

        foreach(var s in s_timestamps)
        {
            //for every timestamp in first timeline find the nearest one from r
            var nearest_r = r_timestamps.OrderBy(r => Math.Abs(r - s)).First();

            //if that is closer than allowed offset
            if ((Math.Abs(nearest_r - s)) <= max_tolerable_offset * 10000)
            {
                //so now I need to find nearest s mark for this r mark
                var closest_s = s_timestamps.OrderBy(s=> Math.Abs(s- nearest_r )).First();

                //if they are mutually in love, marry them
                if (closest_s == s)
                    alignedPairs.Add(s, nearest_r);
            }
        }
</code>```

Body:
Here is my solution in C#, works good enough for my purposes:

///compute reasonably aligned pairs
        var max_tolerable_offset = 500; //do not match more then 500 miliseconds distant timestamps

        Dictionary<long, long> alignedPairs = new Dictionary<long, long>();

        foreach(var s in s_timestamps)
        {
            //for every timestamp in first timeline find the nearest one from r
            var nearest_r = r_timestamps.OrderBy(r => Math.Abs(r - s)).First();

            //if that is closer than allowed offset
            if ((Math.Abs(nearest_r - s)) <= max_tolerable_offset * 10000)
            {
                //so now I need to find nearest s mark for this r mark
                var closest_s = s_timestamps.OrderBy(s=> Math.Abs(s- nearest_r )).First();

                //if they are mutually in love, marry them
                if (closest_s == s)
                    alignedPairs.Add(s, nearest_r);
            }
        }


问:
How to divide work to a network of computers?
Imagine a scenario as follows: Lets say you have a central computer which generates a lot of data. This data must go through some processing, which unfortunately takes longer than to generate. In order for the processing to catch up with real time, we plug in more slave computers.

Further, we must take into account the possibility of slaves dropping out of the network mid-job as well as additional slaves being added. The central computer should ensure that all jobs are finished to its satisfaction, and that jobs dropped by a slave are retasked to another.

The main question is: What approach should I use to achieve this?

But perhaps the following would help me arrive at an answer:
Is there a name or design pattern to what I am trying to do?

What domain of knowledge do I need to achieve the goal of getting these computers to talk to each other? (eg. will a database, which I have some knowledge of, be enough or will this involve sockets, which I have yet to have knowledge of?)

Are there any examples of such a system? The main question is a bit general so it would be good to have a starting point/reference point.

Note I am assuming constraints of c++ and windows so solutions pointing in that direction would be appreciated.

答:
As noted by other answers, this field has been known as distributed computing, grid computing, cluster computing, and high performance computing.

Let me add the distinction that, when a system can be resized after start to match the workload, it is said to be "elastic", and this is different from traditional grid computing.  That is one of the (non-marketing) reasons for the term "cloud computing": the user does not need to plan for capacity, and the number and location of the machines carrying out the computation remain featureless to him as a cloud.

Also, your requirement that the master re-schedules failed tasks is called the "fault tolerance" property of that system. (Mandatory link to this cartoon)

What approach should you use to build your own, private cloud? In my order or preference:

Don't build your own cloud, use the infrastructure provided by others.  Amazon calls this Virtual Private Cloud, Rackspace just Private Cloud; I am sure you can find other offers and compare.

Don't build your own distributed computing engine, use the engine provided by others.  If you insist on using your machines, use at least as much software as possible that is provided and tested by others.  You can use Hadoop from C++ via the Pipes interface or from any executable via the Streaming API.  There is a similar Streaming interface on Spark.

Don't code all components from scratch, use components from the community.  If, for some reason, you have read so far and want to roll out your own cloud components, don't start from C++'s standard library.  The main components you will need are:

a queuing system, as noted in a comment, to send tasks from the master to the processing nodes, and to send result confirmations from processing nodes to the master

a distributed file system, so that processing nodes can access the data to operate on.

There are many alternatives for both. For queuing, RabbitMQ has a Windows installer, as does ZeroMQ. For distributed filesystems, I have really not enough experience on Windows: it looks like you can organize SMB shares into a DFS, but I can't give you any hint here. You could think, as noted in another answer, to use a distributed database such as MongoDB for the data; it does run on Windows.

You could also think about using MPI (usually the OpenMPI implementation, usually through its Boost wrapper), but notice that MPI programs are neither elastic nor fault tolerant per se; you need to take care of that yourself (at least they provide some mechanisms to achieve this).  That is why I would recommend to you first to evaluate a framework for distribution that does have such properties.


问:
Why elseif instead of else if?
Few days ago I stopped on some PHP's developers quide (for contributors to particular project) and it stated, that elseif must be strictly used instead of else if -- without giving any reason, why?

Can someone clarify this? I don't see neither much difference nor any argument supporting this.

Info: I believe, there are more languages, than just PHP, that this problem strikes, that's why I asked here, not on Stack Overflow. Feel free to migrate, if necessary.

答:
The behavior when using curly brackets is exactly the same.  However when not using curly brackets but colon instead, the following will not compile:

```<code>if($a > $b):
    echo $a." is greater than ".$b;
else if($a == $b): // Will not compile.
    echo "The above line causes a parse error.";
endif;
</code>```

I assume that the reason for preferring elseif over else if is either to be able to switch to and from curly brackets without creating a compile error or, probably more likely, it is a stylistic choice and prefers that only elseif is used.

According to the php documentation:

Nota: Note that elseif and else if will only be considered exactly the
  same when using curly brackets as in the above example. When using a
  colon to define your if/elseif conditions, you must not separate else
  if into two words, or PHP will fail with a parse error.

Title: Why elseif instead of else if?

Body:
The behavior when using curly brackets is exactly the same.  However when not using curly brackets but colon instead, the following will not compile:

if($a > $b):
    echo $a." is greater than ".$b;
else if($a == $b): // Will not compile.
    echo "The above line causes a parse error.";
endif;

I assume that the reason for preferring elseif over else if is either to be able to switch to and from curly brackets without creating a compile error or, probably more likely, it is a stylistic choice and prefers that only elseif is used.

According to the php documentation:

Nota: Note that elseif and else if will only be considered exactly the
  same when using curly brackets as in the above example. When using a
  colon to define your if/elseif conditions, you must not separate else
  if into two words, or PHP will fail with a parse error.


问:
Architecture for dashboard showing aggregated stats
I'd like to know what are common architectural pattern for the following problem.

Web application A has information on sales, users, responsiveness score, etc. Some of this information are computationally intensive and or have a complex business logic (e.g. responsiveness score).

I'm building a separate application (B) for internal admin tasks that modifies data in web application A and report on data from web application A.

For writing I'm planning to use a restful api. E.g. create a new entity, update entity, etc.

In application B I'd like to show some graphs and other aggregate data for the previous 12 months. I'm planning to store the aggregate data for each month in redis.

Some data should update more often, e.g every 10 minutes.

I can think of 3 ways of doing this.

A scheduled task in app B that connects to an api of app A that provides some aggregated data. Then app B stores it in Redis and use that to visualise pages. Cons: it makes complex calculation within a web request, requires lot's of work e.g. api server and client, storing, etc., pros: business logic still lives in app A.

A scheduled task in app A that aggregates data in an non-web process and stores it directly in Redis to be accessed by app B.

A scheduled task in app A that aggregates data in a non-web process and uses an api in app B to save it.

I'd like to know if there is a well known architectural solution to this type of problems and if not what are other pros/cons for the solution I've suggested?

答:
I would do it the following way:

Using and ETL tool and scheduled task for example, I'd get the data from app A, and store it in it's most raw form.

From that raw data, I'd use app B to do all of the heavy calculations and displaying.

This keeps the data available and ready to manipulate the way you want it, without having to use app A all of the time.

Keep the applications separate, and just store and use the data as needed, for simplicity.


问:
How would you introduce an agile methodology like scrum?
If you've found agile and walk into a workplace that doesn't particularly follow any methodology and they are resistant to change (as most people usually are), how would you introduce an agile methodology like scrum?

NOTE:

Well, I've phrased it as a hypothetical question, but it isn't.

I'm not very confident about Agile myself

答:
The best way to introduce agile is to show them that their practice of waterfalling doesn't quite cut it.

Now if they don't have any process then investigate then prove to them that their lack of a process causes problems. Then you introduce agile as something which brings some order into chaos without tying everybody's hands with rigid processes.


问:
Simplicity-efficiency tradeoff
The CTO called to inform me of a new project and in the process told me that my code is weird.

He explained that my colleagues find it difficult to understand due to the overly complex, often new concepts and technologies used, which they are not familiar with. He asked me to maintain a simple code base and to think of the others that will inherit my changes.

I've put considerable time into mastering LINQ and thread-safe coding. However, others don't seem to care nor are impressed by anything other than their paycheck.

Do I have to keep it simple (stupid), just because others are not familiar with best practices and efficient coding? Or should I continue to do what I find best and write code my way?

答:
As great and efficient as new technologies are sometimes, efficiency goes down the drain if your team has to spend hours on trying to understand your code.

Neat, structured and simple code is the easiest to maintain, which makes the team and business more efficient, therefore more profitable.

Implementing or just keeping up with new technologies/methods are definitely important, but if it comes at the cost of getting things done, then more focus needs to be placed on getting everyone else trained up, otherwise nobody wins.

Ultimately, it's your bosses call, which means you'll have to convince him, that it's the best for the business.

Title: Simplicity-efficiency tradeoff


问:
Redis strategy for activity log data
Our application requires an activity log of actions that a user has done. For example:

3/19/2013

-------------

9:37 AM Chuck Norris scrapped 3 robots.

9:15 AM Chuck Norris fought 3 robots.

Currently this is done with a gigantic query that compiles all of a user's activity on a given day. The query is so slow that that application literally forbids you from looking at more than a single day's activity at a time. These results could be aggressively cached in Redis.

My question is: what is a good Redis key strategy for storing these activities?

I need to be able do a lookup primarily based on the user ID and a date range. I've played with the following possibilities, but nothing has really leaped out at me as the optimal solution.

```<code>-- psuedo-code, obviously --
HMSET user:5345:activity date "3/19/2013" time "9:37 AM" action "Some action"
LPUSH user:5345:activity (json)
LPUSH user:5345:activity:2013:03:19 (json)
</code>```

All three of these have significant tradeoffs. Assume a user hasn't logged in for four months - they might actually want to see their activity from four months ago at the top of the list. The second option gives me that, but there are trade-offs in that direction as well (like not being able to specifically query by date).

Any thoughts on a better way to approach this?

答:
I'm one of the authors of the Feedly package which was mentioned.

We built a solution for the 2nd largest online fashion community and open sourced our approach:
https://github.com/tschellenbach/Feedly
It's currently the largest open source library aimed at solving this problem.
You can use both Redis and Cassandra as storage backends.

Our redis storage backend uses sorted sets for data storage.
https://github.com/tschellenbach/Feedly/tree/master/feedly/storage/redis
In addition we use pubsub capabilities for the realtime components.

The same team which built Feedly also offers a hosted API, which handles the complexity for you. Have a look at getstream.io There are client libraries for Python, PHP, Node and Ruby. (This is based on Cassandra and therefore substantially cheaper to operate than running your own system using Redis)

In addition have a look at this high scalability post were we explain some of the design decisions involved:
http://highscalability.com/blog/2013/10/28/design-decisions-for-scaling-your-high-traffic-feeds.html

This tutorial will help you setup a system like Pinterest's feed using Redis. It's quite easy to get started with.

To learn more about feed design I highly recommend reading some of the articles which we based Feedly on:

Yahoo Research Paper

Twitter 2013 Redis based, with fallback

Cassandra at Instagram

Etsy feed scaling

Facebook history

Django project, with good naming conventions. (But database only)

http://activitystrea.ms/specs/atom/1.0/ (actor, verb, object, target)

Quora post on best practises

Quora scaling a social network feed

Redis ruby example

FriendFeed approach

Thoonk setup

Twitter's Approach

Title: Redis strategy for activity log data


问:
Securing web services
How to approach securing webservices? I can think of using one of the two approaches below

sending a user name password in every request for validation

Sending a time based token (GUID or some similar long string)

In the first approach I have to query a database every time in most cases an RDBMS to authenticate a user.

In the second I now make a user name password authentication only once and then return to the user a time based token. All future business requests are authenticated via this token. On expiry this token will need to be recreated by the calling client.

Both approaches seem to have their own pros and cons. Which one would you recommend in which circumstances and what would be your reasons for the same? Perhaps a specific condition where one favors the other.

答:
Use HTTPS.

Seriously. Use it. There is no point in discussing the security of a web service where any password or token will be passed in plain text from the client to the server.

Prefer a mechanism which is already provided by the framework. For example, WCF allows you to implement authentication very easily, doing all the transport-level hard work itself. So don't reinvent the wheel.

There is nothing wrong in authenticating at every request. Instead of speculating about the impact on the database, measure it, profile it and then take the decision based on actual data.

Title: Securing web services


答:
Besides this answer, in both PSR2.0 and PEAR coding standards the use of elseif instead of else if is specified so that all control keywords look like single words:

```<code><?php
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}
</code>```

The keyword elseif SHOULD be used instead of else if so that all
  control keywords look like single words

Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md#51-if-elseif-else

Title: Why elseif instead of else if?

Body:
Few days ago I stopped on some PHP's developers quide (for contributors to particular project) and it stated, that elseif must be strictly used instead of else if -- without giving any reason, why?

Can someone clarify this? I don't see neither much difference nor any argument supporting this.

Info: I believe, there are more languages, than just PHP, that this problem strikes, that's why I asked here, not on Stack Overflow. Feel free to migrate, if necessary.

Body:
Besides this answer, in both PSR2.0 and PEAR coding standards the use of elseif instead of else if is specified so that all control keywords look like single words:

<?php
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}

The keyword elseif SHOULD be used instead of else if so that all
  control keywords look like single words

Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md#51-if-elseif-else


答:
By making the case, just like anything else.

You start by asking yourself this: What are the problems that our current methodology has, and how would agile help fix those problems?

It may not be an easy sale.  Going Agile completely requires a different mindset, a different way of doing things, and a different corporate culture.  Specifically, the Agile Manifesto list these characteristics of Agile development:

Early and continuous software delivery

Changing requirements

Deliver working software frequently

Customers and developers working together daily

Autonomous, highly-motivated developers with the tools they need to succeed

Face-to-face conversation

Sustainable development

Continuous attention to technical excellence
and good design

Simplicity

Self-organizing teams

Tuning and adjustment of the development process

Most companies don't have all of these characteristics already; if they did, they'd already be agile.  But chances are good that your company already has some.  Evaluate each bullet based on your company's relative strengths, and start a conversation how you can begin incorporating some of these principles into the development process.

Title: How would you introduce an agile methodology like scrum?

Body:
If you've found agile and walk into a workplace that doesn't particularly follow any methodology and they are resistant to change (as most people usually are), how would you introduce an agile methodology like scrum?

NOTE:

Well, I've phrased it as a hypothetical question, but it isn't.

I'm not very confident about Agile myself


问:
Efficient algorithm to find a the set of numbers in a range
If I have an array of sorted numbers and every object is one of the numbers or multiplication. For example if the sorted array is [1, 2, 7] then the set is {1, 2, 7, 1*2, 1*7, 2*7, 1*2*7}. As you can see if there's n numbers in the sorted array, the size of the set is 2n-1.

My question is how can I find for a given sorted array of n numbers all the objects in the set so that the objects is in a given interval. For example if the sorted array is [1, 2, 3 ... 19, 20] what is the most efficient algorithm to find the objects that are larger than 1000 and less than 2500 (without calculating all the 2n-1 objects)?

答:
To search for a "sweet spot" such as this, you generally use a priority queue.  The idea being is that you have a list sorted by a specific requirement.  The more similar a solution is to a requirement, the more likely it will be chosen from the priority queue to search for more solutions.

In this case, your solution would be a series of indices in which each pertains to a number in your array.  So in other words for the solution 2*7, you'd have an array [1,2].  You could also use a binary number with n bits if you prefer.  The priority queue, in order to determine which is best, it should mulitply all numbers referred to by the indices together.  The sweet spot in this case is going to be the place where you are likely to find most solutions, so in this case it would be the average between the maximum and the minimum, 1750.

The algorithm goes as follows:

Add each number in its own solution array and add it to the priority queue.

Then, starting with the first (the closest to (maximum+minimum)/2), remove it from the priority queue and for each index not included in the solution, add it to the solution and reinsert into the priority queue.

If you find that the current product times each new number exceeds the maximum, you don't even add it to the queue.  If it is less than the minimum, then you do nothing with it.

If it is within the minimum and the maximum, do something with it.

Continue until you have them all.

In this way, you're reducing your solution search for values near your average.  You should be getting most of your solutions immediately this way, but in order to get them all, you will have to search the entire solution space 2^n-1.

Lets do a quick test for a small range of values [1,2,3,4].  I want to find all solutions whose values are between 10 and 12, then I'd first by adding all numbers in their own solution and putting them in the priority queue.  The priority would then look like:
[[4],[3],[2],[1]].

I take the first [4], and I append 3, 2, and 1 in their own solutions and add it to the priority queue.  The priority queue then becomes:

```<code>[[4, 3], [4, 2], [4, 1], [4], [3], [2], [1]]
</code>```

I see that I've already got my first value [4, 3]!  Lets continue and see what happens:

```<code>[[4, 3, 1], [4, 2], [4, 1], [4], [3], [2], [1]]
</code>```

Notice that [4, 3, 2] was too large and was not added.  I found another solution [4, 3, 1]!

If something isn't clear ask and I'll try to clarify.

Hope that helps.

Body:
To search for a "sweet spot" such as this, you generally use a priority queue.  The idea being is that you have a list sorted by a specific requirement.  The more similar a solution is to a requirement, the more likely it will be chosen from the priority queue to search for more solutions.

In this case, your solution would be a series of indices in which each pertains to a number in your array.  So in other words for the solution 2*7, you'd have an array [1,2].  You could also use a binary number with n bits if you prefer.  The priority queue, in order to determine which is best, it should mulitply all numbers referred to by the indices together.  The sweet spot in this case is going to be the place where you are likely to find most solutions, so in this case it would be the average between the maximum and the minimum, 1750.

The algorithm goes as follows:

Add each number in its own solution array and add it to the priority queue.

Then, starting with the first (the closest to (maximum+minimum)/2), remove it from the priority queue and for each index not included in the solution, add it to the solution and reinsert into the priority queue.

If you find that the current product times each new number exceeds the maximum, you don't even add it to the queue.  If it is less than the minimum, then you do nothing with it.

If it is within the minimum and the maximum, do something with it.

Continue until you have them all.

In this way, you're reducing your solution search for values near your average.  You should be getting most of your solutions immediately this way, but in order to get them all, you will have to search the entire solution space 2^n-1.

Lets do a quick test for a small range of values [1,2,3,4].  I want to find all solutions whose values are between 10 and 12, then I'd first by adding all numbers in their own solution and putting them in the priority queue.  The priority would then look like:
[[4],[3],[2],[1]].

I take the first [4], and I append 3, 2, and 1 in their own solutions and add it to the priority queue.  The priority queue then becomes:

[[4, 3], [4, 2], [4, 1], [4], [3], [2], [1]]

I see that I've already got my first value [4, 3]!  Lets continue and see what happens:

[[4, 3, 1], [4, 2], [4, 1], [4], [3], [2], [1]]

Notice that [4, 3, 2] was too large and was not added.  I found another solution [4, 3, 1]!

If something isn't clear ask and I'll try to clarify.

Hope that helps.


问:
Do input template languages exist?
When I have to create some textual representation of data, I can use a template language, so that my code does not have to worry about the structure of the output file - I can sometimes even write code that's independent of whether the output is XML, LaTeX or any other plain text. A simple example:

Template (in separate file):

```<code><someXmlTag>
$variableName
</someXmlTag>
</code>```

Code:

```<code>Template(temstring).substitute(variableName="value")
</code>```

Result (written to output file):

```<code><someXmlTag>
value
</someXmlTag>
</code>```

I want to do the same, but in the opposite direction. I have XML or plain text or whatever files to input. I want to describe the input structure in a separate file that looks like the input but has these variable declarations in it, and I want to handle it with code that's independent of the structure.

Has this been done before? What approach was used and how did it work out?

(We usually handle XML input by using an XML parser library to describe the input structure in program code, handle plaintext input by writing regexes in code, and don't handle LaTeX input because LaTeX can't really be parsed.)

答:
The closest I think you're going to find is web scraping software.  Most of those use xpath or similar rather than a template, but I'm not familiar with the entire field.

It wouldn't be terribly difficult to write your own, though, especially if you limit your templates to simple substitution, no loops or if statements, and you make all your variables strings.  You're basically looking for a long string of fixed text, followed by a unknown-length string to put into the variable, followed by another fixed string.  I would estimate less than a day to do a bare bones proof of concept.

Title: Do input template languages exist?


问:
Why are interfaces called interfaces?
From what I understand so far, an interface is a list of methods that need to be implemented by whoever wishes to use that interface.

If so, would it make any difference to call it a specification instead of interface, or is it more sophisticated than a specification?

答:
The definition of interface on oxforddictionaries.com is

A point where two systems, subjects, organizations, etc. meet and
  interact.

In programming, the 'two systems' are the class that is using the interface (the client), and the class that is 'hidden behind' the interface, i.e. the class that implements the interface. In this way an interface is a point where two classes interact.

Title: Why are interfaces called interfaces?


问:
"Default approach" when creating a class from scratch: getters for everything, or limited access?
Until recently I always had getters (and sometimes setters but not always) for all the fields in my class. It was my 'default': very automatic and I never doubted it. However recently some discussions on this site made me realize maybe it's not the best approach.

When you create a class, you often don't know exactly how it's going to be used in the future by other classes.

So in that sense, it's good to have getters and setter for all of the fields in the class. So other classes could use it in the future any way they want. Allowing this flexibility doesn't require you to over engineer anything, only to provide getters.

However some would say it's better to limit the access to a class, and only allow access to certain fields, while other fields stay completely private.

What is your 'default' approach when building a class from scratch? Do you make getters for all the fields? Or do you always choose selectively which fields to expose through a getter and which to keep completely private?

答:
Unless your class is Plain Old Data, start by defining the interface its clients will see. This is a PITA in C++, not so bad in Java. Program to the interface; hide the class - if need be - behind a factory object.

Thus you can distinguish between changes you make to the class that don't affect its clients (these change the class but not the interface) and those that do affect the clients (these change the interface).

An intelligent linker (such as Component Pascal/Black Box possessed) should enable you to avoid rebuilding clients in the former case. I have no idea whether Java does this. You can do this in C++, but you have to be careful how you arrange and use your header files.


问:
Benefits of porting C library to C++
Say we take any C library such as libpng or libvorbis and convert it so that it compiles as C++ (only the minimum changes to make it compile as C++ code).

Can the compiler do extra optimizations when its C++ code? Is there any sort of benefit to be gained by porting the code to C++? What are the downsides that might cancel out these benefits?

答:
No, and that assuming the code will compile (you will have to make changes, C++ is not completely compatible with C, for example void * values cannot be assigned to other pointer types, and there are new keywords). In best case, there will be absolutely no difference. C++ doesn't add any new undefined behaviors the compilers can depend on. I don't think it removes them either, but I may be wrong here.

In worst case, you will lose the performance. The code that depends on C99's restrict keyword cannot depend on it anymore, as C++ doesn't have restrict keyword.

Also, the compiler has to enable exceptions support, even if it's unused. While I don't think it's needed for the code (it doesn't use C++ types or C++ functions), some compilers still compile the code to handle stack unwinding, which may lower the performance.

Many compilers implement both C and C++ (and probably other languages as well). The C constructs are compiled identically to C++ constructs, as there is no reason for them to behave differently.

Title: Benefits of porting C library to C++


答:
No, and there is one disadvantage to consider: name mangling. C has very well-defined linking semantics. C++ is by design compiler-specific: this means that converting to C++ may actually hurt you:

You can link with only one compiler/linker.

The code will not take advantage of any C++ features given the constraints of your question.

Introduced risk of new bugs because you are changing the compiler and language.

C++ is linker-compatible with C in most cases anyway, so a C++ program can most likely link to a C library without recompiling the library.

Title: Benefits of porting C library to C++

Body:
Say we take any C library such as libpng or libvorbis and convert it so that it compiles as C++ (only the minimum changes to make it compile as C++ code).

Can the compiler do extra optimizations when its C++ code? Is there any sort of benefit to be gained by porting the code to C++? What are the downsides that might cancel out these benefits?


答:
First, I'd inquire as to what do those that would be using this methodology think of it, what experiences have they had with it, etc. so that I can know the background of what perspective do these people have.

Second, I'd likely see how much of a shift would something like Scrum be on this team?  Is there a way to break this down so that it isn't a big shift all at once?  Piece by piece is a good way to describe the methodology here but also contrasting this to how things are currently done is another part to this.

Third, find a good Scrum Master that could help get management buy-in as well as things initially set up to give success a good chance as sometimes it isn't easy trying to get another chance to launch something.


答:
What is your 'default' approach when building a class from scratch? Do
  you make getters for all the fields? Or do you always choose
  selectively which fields to expose through a getter and which to keep
  completely private?

Getters and setters are a sign of a deeper problem, that being that the programmer is focused on the data the class holds, not the behaviour it encapsulates.

The "default" approach should be to not be thinking about the internal data of the object in the first place at all. If you don't start off by defining internal variables then there are no variables to worry about exposing in through getters or setters.

Be thinking instead of the behaviour the object is attempting to represent in the model. Expose that behaviour through methods with meaningful names. Only then think about how the object is going to carry this behaviour and if it needs any private variables to do this (it may not)

My default steps -

Think what in the business domain this object is representing and
define a class.

Think of the first behaviour this object is responsible for, and
define a method that exposes this behaviour to the outside world.

Work out how to carry out this behaviour, what internal variables
you need (if any).

Either finish the class (nothing wrong with an object with only one
method) or if there are closely related behaviour define another
public method.

Refactor if necessary (you might find that the class if growing too
big, so you split it off).

99.9% of the time after you have done that you will have no internal variables left over to even consider a getter or setter for.


问:
Algorithm for optimal combination of two variables
I'm looking for an algorithm that would be able to determine the optimal combination of two variables, but I'm not sure where to start looking.

For example, if I have 10,000 rows in a database and each row contains price, and square feet is there any algorithm out there that will be able to determine what combination of price and sq ft is optimal.

I know this is vague, but I assume is along the lines of Fuzzy logic and fuzzy sets, but I'm not sure and I'd like to start digging in the right field to see if I can come up with something that solves my problem.

答:
First, you need to define some sort of evaluation function that can tell you the value of a given combination.  For example, are you trying to maximize price per square foot?  Square feet per dollar?  Something else?

Once you have such an evaluation function, simply calculate the result for each combination of factors in your dataset and then select the combination of parameters that rates highest (or lowest).


答:
Not really. There's no purpose in moving to C++ if you don't make use of the C++ language and library features. It would be effort for nothing, and there are some costs, like ABI.

OTOH, if you do make use of the language features (especially RAII, EH and templates), you will get a far superior program. Many problems can be far easier expressed in C++ than C, and many of them more efficiently too.

Ultimately, moving from C to C++ is an investment. You pay in dev time, probably quite a bit since they're nowhere near as similar as they seem on the surface. You get out vastly improved program. But you have to pay all the investment or it doesn't pay off. It would be like wanting to build a factory but asking for a return after you finished only two walls. You have to build all the walls, build a roof, buy the machinery, hire people to run the factory, find a design to manufacture... then you can start making a profit.

Title: Benefits of porting C library to C++


答:
You might be looking for Pareto efficiency/optimality.

This will allow to select only pairs that are not worse than anything else. From those, you can then pick those that are best for you. The major advantage of this algorithm is that it can be applied for more than two variables.

Title: Algorithm for optimal combination of two variables

Body:
I'm looking for an algorithm that would be able to determine the optimal combination of two variables, but I'm not sure where to start looking.

For example, if I have 10,000 rows in a database and each row contains price, and square feet is there any algorithm out there that will be able to determine what combination of price and sq ft is optimal.

I know this is vague, but I assume is along the lines of Fuzzy logic and fuzzy sets, but I'm not sure and I'd like to start digging in the right field to see if I can come up with something that solves my problem.