问:
Alan Kay: "The Big Idea is Messaging"
Alan Kay said "OO" was about messaging, not objects and drew a parallel to biological cells.

His views are enticing, but vague.  The way I understand it is something like a Cellular Automata.

In a Cellular Automata there's a grid of cells that can be in a variety of states.  Then an update event is sent to all the cells.  In response, the cells update their state based on their own state and the state of their neighbors.

So if we assume...

```<code>Grid => Software System
Cell => Object
Update Rule => Event/Message
</code>```

Then we have a starting point.  Locality differs (unless we define neighbors as objects that are connected), and there isn't one update rule, but a variety of messages/events that objects can respond to.

Having used cellular automata, I'm aware of their power and the awesome global emergence that arises from local interactions.  Thinking of this applied to the sphere of objects is breath-taking.

Or perhaps to put it another way, it's an extreme event driven system in which a network of objects forms the architecture, (global?) events define the information flow, and the interaction of these objects defines the system behavior.

Is this understanding correct?  If not, I'd love clarification and even examples of code written in this message system (vs. code that's not), to make this concrete.

答:
The key to Alan Kay's view is the reason why a message is sent.

When an object of class A sends a message to an object of class B because A wants B to do something specific, that isn't OO (according to Kay's vision.) If A is sending the message to inform B that something has happened (rather than telling it to do something,) that is OO.

A good example of this is an onClick method that informs something that a button was clicked.

A bad example would be the append method on a container. This isn't OO programming, rather it is bog standard modular programming. There's nothing wrong with modular programming mind you, but it is different than OO.

EDIT

I feel the need to defend the above somewhat... Refer to Alan Kay's email that was posted in the question (here). Notice quotes like, "I wanted to get rid of data." Notice how he keeps coming back to the notion of avoiding data in favor of sending messages to objects.

When you tell a container to append, you are explicitly dealing with data. You care whether or not the container's size attribute increased. Whenever a function is called because the caller wants to ensure the called's post-condition, that is a reference to data, either explicit or implicit.

Mr. Kay wanted to avoid that, and this means that OO is about sending messages to inform objects of things happening, not to force them to change their state.

Title: Alan Kay: "The Big Idea is Messaging"


问:
XSLT equivalent for JSON
I was interested in finding (or if necessary developing) an XSLT equivalent for JSON.

As I have not found any, I was considering the possible query language to use for matching JSON paths so as to apply templates (from JavaScript) when there was a match (probably just checking an array of matching patterns in order, and stopping at the first template which matches, though allowing for the equivalent of xsl:apply-templates to keep templates going for children).

I am aware of JSONPath, JSONQuery, and RQL as JSON query languages (though I was not fully clear on whether RQL supported absolute and relative paths). Any suggestions on factors to consider and relative advantages of each toward such a usage.

答:
XML : XSLT :: JSON : x. What is x ?

The most facile answer would be x = JavaScript. Though you could make a case for this, it feels unsatisfying. Even though XSLT is technically Turing complete, there is a poor correspondence between the declarative style of XSLT and the more imperative or functional styles seen in JavaScript.

There are a few standalone JSON query languages, like JSONPath, JSONiq, and RQL which might stand in for the middle ground of XML : XPath :: JSON : y (or possibly, XQuery rather than XPath). And every JSON-focused document database has a JSON-related query language.

But the reality is, despite there being a few contenders for the full XSLT position, such as SpahQL, there are no generally accepted, broadly supported JSON equivalents to XSLT.

Why?

With all the JSON in the world, why isn't there a (more direct) analog to XSLT? Because many developers view XSLT as a failed experiment. Any search engine will lead to to quotes like "XSLT is a failure wrapped in pain." Others have argued that if it were just better formatted, it would be more popular. But interest in XSLT has generally diminished over the years. Many tools that support it support only version 1.0, which is a 1999 specification. Fifteen year old specs? There is a much newer 2.0 spec, and if people were enthusiastic about XSLT, it would be supported. It isn't.

By and large developers have chosen to process and transform XML documents with code, not transformation templates. It is therefore unsurprising that when working with JSON, they would also by and large choose to do that in their native language, rather than adding an additional "foreign" transformation system.

ContentLicense: CC BY-SA 3.0

Title: XSLT equivalent for JSON


问:
Choosing a random integer in a range such that it doesn't equal a particular number
Given an integer range and a number within that range, what's a reasonably robust and efficient way to randomly select a new number within the range such that it's not equal to the given number?

Whenever I need to do this, I usually use something like:

```<code>// Randomly choose an integer within an inclusive range with the condition
// that the result not equal the previous number chosen
// INPUT: lastNum is an int in the range [minVal, maxVal]
int ChooseNewNumber(lastNum){

    minVal = 0;
    maxVal = N; // This would usually be a value like someContainer.size - 1
    intervalLength = maxVal - minVal + 1;

    // Assume RandomInt...() is an existing function that lives up to its name
    int newNum = RandomIntWithinInclusiveRange(minVal, maxVal);

    if (newNum == lastNum){
        // Add a random offset to newNum and wrap around if necessary
        newNum = (newNum+RandomIntWithinInclusiveRange(1, intervalLength - 1)) % (maxVal+1);
    }

    return newNum;
}
</code>```

This works and it seems to avoid the introduction of any bias in the newNum == lastNum case, but it's a bit clunky. Is there a cleaner way to accomplish the same thing?

EDIT: as coredump pointed out, the method above fails if minVal != 0. Just for reference, the line:

```<code>newNum = (newNum+RandomIntWithinInclusiveRange(1, intervalLength - 1)) % (maxVal+1);
</code>```

should be:

```<code>new = ((new + RandomIntWithinInclusiveRange(1, intervalLength - 1) - minVal) % intervalLength) + minVal;
</code>```

I realize this mistake gave the impression that minVal might always be 0; sorry about that.

答:
You can also go for the scrabble method:

Generate a list of numbers from 1-N;

Select a random item from this list;

Remove this item from the list;

Use the modified list when you need your next number.

It is simply impossible to draw the same number twice in a row, because the number is not in the list anymore. It is similar to what happens in games like Scrabble or Rummy.

in C# code (untested):

```<code>//do this during the setup phase
List<int> numberRange = Enumerable.Range(0, N).ToList();
Random random = new Random(); //Or your random implementation of choice

//Do this when you need a number
int index = random.Next(numberRange.Count);
int chosenNumber = numberRange[index];
numberRange.Remove(chosenNumber);
return chosenNumber;
</code>```

Please note that this scales linearly in memory with N, and in time with N when generating the list. It is to be used if you need to ensure that you don't have the same item twice. If you don't want to pull the same number twice in a row (but you still want the number before the last number to be an option), you need to keep the original list and remove the last item using Except() BEFORE you generate your index.

Body:
You can also go for the scrabble method:

Generate a list of numbers from 1-N;

Select a random item from this list;

Remove this item from the list;

Use the modified list when you need your next number.

It is simply impossible to draw the same number twice in a row, because the number is not in the list anymore. It is similar to what happens in games like Scrabble or Rummy.

in C# code (untested):

//do this during the setup phase
List<int> numberRange = Enumerable.Range(0, N).ToList();
Random random = new Random(); //Or your random implementation of choice

//Do this when you need a number
int index = random.Next(numberRange.Count);
int chosenNumber = numberRange[index];
numberRange.Remove(chosenNumber);
return chosenNumber;

Please note that this scales linearly in memory with N, and in time with N when generating the list. It is to be used if you need to ensure that you don't have the same item twice. If you don't want to pull the same number twice in a row (but you still want the number before the last number to be an option), you need to keep the original list and remove the last item using Except() BEFORE you generate your index.


问:
Getters and Setters unclear example
I know autmatic getters and setters are considers bad as they tend to break object's encapsulation. They also move the work that should have been done within the object outside.

Allen Holub is a big advocate of avoiding them. In one of his presentations he gives this example as bad design:

Here currency conversion happens outside the Money class and is spread across the application wherever conversion is needed.

As a fix he introduces this:

It makes sense to me that a Money object now uses Currency object and Money arithmetics  are done within the Money class, but this line m=currency.convertToYourCurrency(m) I don't understand.

How will the Currency method public Money convertToYourCurrency(Money money); know what's the argument's currency? Is it going to use a getter? If it delegates to Money for conversion why bother calling it from within Money to begin with?

Did Mr. Holub make a typo on his slide or am I missing something obvious?

Link to the class: https://vimeo.com/user22258446/review/79095046/9c0ffa90c8 this is from ~44:22

答:
I think his first example is a little contrived. If you've really gotten yourself into that pickle, you probably didn't think hard enough about the problem in the first place.

The "largerThan" and "addTo" methods make sense because rather than carry two values & imposing some semantics outside the class on the separate values, he's defining the operations on value / currency pair through the class operations. And that's a good thing, because the meaning of "largerThan" or "addTo" are encapsulated in the class. Which is (probably) better than leaving the definition (and possible misuse) to the client.

But an alternate approach would be to express all money values in some canonical currency, do all your operations in that common currency, and then convert it to the desired currency at the last minute.

The part where he dispenses with the getter in favor of a write to method is ... something. One could argue that introduces a dependency on the Writer interface rather than allowing the client to get the value and do with it what it wants.

I've done that before, but not as a general practice.

For example, if you were going to serialize Money to JSON, would you introduce a "toJSON" method that accepts a "serializer" object? Now that class has another dependency & an more semantics to manage. There's potential for blowing up the interface with all the different integration points.

...e.g. to forge on, how would you save a Money to a database as a part of some transaction?

So he's making an interesting point, and I think his example of rolling up logical operations into the class is a good one. But the idea of completely dispensing with getters is an interesting refactoring, but not one that I commonly see.

...

I think the core idea here is that he has an example where the operations are spread across 4 classes: Money, Currency, CurrencyConverter, and whatever client is pulling it all together.

But really, the Currency class has tighter usage if you eliminate CurrencyConverter and move it's logic inside Currency so that the currency type and operations on that type are bundled together & hidden from the outside world.

Then he pulls the operations on the value / currency pair and bundles those together inside the Money class, and hides them from the outside world.

So IMHO this looks more to me like an example of improving poor or weak encapsulation more than a condemnation of getters -- the getters here are more like accessories to the crime rather than the masterminds. ;)

Title: Getters and Setters unclear example


问:
What is the Bible of Hashing?
Is there a Cormen-like reference on Hashes and Hashing? This particular structure has seen little attention in my CS education for some reason but I'd like to learn more as they seem to be everywhere. I know Cormen covers it but I'm looking for something more specialized and in-depth.</p>

答: My guess learning about hashes is not the same of learning about random number generators (rng) but its very similar field in a way of knowing what differ a real random number from a pseudo-random and the quality about randomness. You probably know about xor-ing an image to hide any kind of data that you could extract from it, so, thats my guess. You need some good seeds for a good hash and knowing about randomness could help.</p>

Title: What is the Bible of Hashing?


问:
In MVC should a model contain subview models?
Some background:

A colleague and myself have different interpretations of MVC which means, given the same problem, we are coming up with radically different solutions. He comes from a Java background where every component of MVC may traditionally model an object and I come from a Haskell background and have little or no experience with OOP.

The problem space:

The problem we are trying to model acts a little bit like a desktop environment. We have a notion of the users session (perhaps their login, their desktop background) and the processes on their desktop (say iTunes, Finder, etc) which each have their own model properties (minimised, etc).

We agree on the following point: we think HMVC is the best representation. We agree that we have two MVC objects, Session (desktop) and Process (application) and that we don't want a Process to have a notion of Session or a backlink.

Once place we disagree on however is the core meaning of MVC and how that affects where we keep the list of processes on the users desktop.

His interpretation:

He argues a very valid point which traditionally is easy to model in code and in our rendering system. He says that the list of processes should be a list of ProcessController objects within SessionController which in turn have their models as separate objects inside them. This means that there is a significant amount of state within both SessionController and SessionModel which is relevant to what SessionView needs to render.

This seems to be very much in harmony with what we were able to read on the internet in a brief search.

My interpretation:

My interpretation requires the largest architectural change and seems harder to implement in the code, but I believe it is more conceptually correct. I would like somebody to explain why this is not the case, or present a different model (if not MVC) that aligns with this interpretation and highlight some strengths and weaknesses for both patterns so we can make the most informed decision (neither of us have a strong background in software architecture).

I see MVC as a triad with three interchangeable components: the Model, the Controller and the View. This agrees with what I am able to read on the internet, and some sources will say things along the lines of like 'views, controllers and models with the same interface should be interchangeable to different effect'. The way I imagine this to work is as follows:

When you swap the model, you are changing the way data is validated or stored

When you swap the controller, you are changing how the page behaves, but not anything which could alter the conceptual data content of the page

When you swap the view, you are changing the way the page is displayed

From this, I reasoned that given any Model and View, swapping only the controller should not change the data the page initially renders because the controller should change only the behaviour and not the 'content' of the page. I think this aligns with the conceptual visualisation of the controller as a 'station controller' in a rail system, a plan of the rail road as the model and the actual physical manifestation and look/feel of the tracks (in different flavours, say 'Real' or 'Virtual 3D') as the view.

Here's where we disagree:

I argue that because the data that will be displayed to the user in the SessionView is changed by the different processes on the desktop (I model the processes as relevant data), the SessionModel should contain the list of instances of ProcessModel. This means that using any random SessionController with the same SessionView should conceptually show the same data (processes on the desktop).

He argues that it makes more sense for a Model to never know about another model. This means that the SessionController would have a list of ProcessControllers within it and each Controller object has a link to its model. Given a SessionView and the same SessionModel but a different SessionController the data displayed to the user should be radically different.

Please argue for/against each interpretation and help us to reach the most informed outcome.

Thanks for your time!

答:
The key in understanding MVC lies in the separation of the responsibilities, as MVC is simply SRP applied to UI code. It separates what data has to be displayed, from how to display it, from how to handle screen events. But an important (and often missed) detail of the original definition of MVC is that it was designed for a far more granular level. For instance, you'd have ButtonModel, ButtonView and ButtonController objects, "just" to present a single button on a screen. Missing this detail is what causes so many different opinions on the subject. You can check the Java Swing architecture to see what I mean.

The point of MVC is to allow the code that serves each responsibility to be changed without affecting the code for the others. For instance, you would be able to switch the rendering of (a component on) the screen without having to touch the data representation nor the event-handling logic. So, to a degree, this goes along with what you say here:

From this, I reasoned that given any Model and View, swapping only the controller should not change the data the page initially renders because the controller should change only the behaviour and not the 'content' of the page. I think this aligns with the conceptual visualisation of the controller as a 'station controller' in a rail system, a plan of the rail road as the model and the actual physical manifestation and look/feel of the tracks (in different flavours, say 'Real' or 'Virtual 3D') as the view.

However, in your context, the level of granularity is off; you have a SessionView that seems to be responsible for a whole screen. At this level, the responsibilities get too coupled to fully separate as intended by MVC, thus it may not provide the full benefits.

Your problem is in separating the three UI responsibilities (rendering, the data and the event-handling) for both sessions and processes, a total of six. Because of the level of granularity of the components (whole screen), this becomes impossible, and causes the dissonance you find yourselves into.

You want to separate the rendering and event-handling responsibilities for both Sessions and Processes, but you'd couple their data. Your colleague wants to decouple the data, but couple the event-handling.

So in the end, this is an SRP problem. My way out would be to decrease the level of granularity down to a point where you can clearly separate Sessions from Processes. If you can't do that due to economics, you guys simply have to weight both sides of the trade-off, choose the least worst, and sign it off as technical debt. This is, after all, what design decisions are all about. :)


答:
How will the Currency method public Money convertToYourCurrency(Money money); know what's the argument's currency? Is it going to use a getter?

One could say that, loosely speaking, the fix is a very simplistic visitor pattern. The Currency object is the visitor that, by the pattern's definition, performs operations on the Money objects. Of necessity the visitor must know\have access to the Money class structure in order to its thing.

If it delegates to Money for conversion why bother calling it from
  within Money to begin with?

The larger point is encapsulating the currency conversion - not making the Money client code do it.

currency conversion code is now re-usable, every Money client does not have to write its own conversion code.

Single Responsibility Principle. One can argue that for the design intent conversion belongs in the Money class.

Title: Getters and Setters unclear example

Body:
I know autmatic getters and setters are considers bad as they tend to break object's encapsulation. They also move the work that should have been done within the object outside.

Allen Holub is a big advocate of avoiding them. In one of his presentations he gives this example as bad design:

Here currency conversion happens outside the Money class and is spread across the application wherever conversion is needed.

As a fix he introduces this:

It makes sense to me that a Money object now uses Currency object and Money arithmetics  are done within the Money class, but this line m=currency.convertToYourCurrency(m) I don't understand.

How will the Currency method public Money convertToYourCurrency(Money money); know what's the argument's currency? Is it going to use a getter? If it delegates to Money for conversion why bother calling it from within Money to begin with?

Did Mr. Holub make a typo on his slide or am I missing something obvious?

Link to the class: https://vimeo.com/user22258446/review/79095046/9c0ffa90c8 this is from ~44:22


问:
Enforcing manual inclusion of a specific header file (banned.h)
Banned.h is a list of ANSI C functions that Microsoft is trying to persuade programmers to deprecate. I already know how to enforce automatic inclusion of banned.h (such as the answer to Ensuring that headers are explicitly included in CPP file). Unfortunately, that answer has an important drawback.

Forced inclusion in project settings always includes the forced header first. Unfortunately, most of Microsoft's own system header files are not banned.h compliant, and many third party library headers are also not banned.h compliant. Microsoft claims that their usage of the banned APIs are safe, and has no intention of changing this situation. The primary way to use the system headers, then, is to include them before banned.h.

One way to solve this is to make a kind of meta_banned.h, which includes all possible system headers that are used anywhere in your project, as well as all the headers for any non-compliant third-party libraries, prior to including the regular banned.h. This is the first thing I did, but it causes an unfortunate hit to compile time because some of the third-party libraries have extensive headers.

We ended up with a hybrid approach--the meta_banned.h includes some system headers, and then the project settings for certain exceptional CPP files include the third-party headers as part of the force-include settings on that particular file. This works, but it's ugly and painful to maintain. The per-CPP-file forced includes in particular seem ugly.

What I really want is a method to ensure that banned.h is included somewhere in each file, not necessarily at the top. As long as it's included at some point, I consider the file compliant. If it's not included, I want to generate a build error. Any suggestions?

答:
Ok, I would never in a million years do this, but you could do something like this:

Force auto inclusion of this:

```<code>// forcebanned.h
#define for "You must include banned.h"
</code>```

Then add this:

```<code>// mybanned.h
#undef for
#include banned.h
</code>```

But don't do that.  Better is to make the inclusion of banned.h a coding standard, and rely on code reviews to catch it.

If you are really insistent on enforcing this technically, you could have a custom build step that grep'd files for "banned.h" prior to compilation, failing the build if the line isn't found. (Or use some static analysis tool that tags deprecated functions.)  Doing so as part of the build keeps your code simpler, and more portable.

Body:
Ok, I would never in a million years do this, but you could do something like this:

Force auto inclusion of this:

// forcebanned.h
#define for "You must include banned.h"

Then add this:

// mybanned.h
#undef for
#include banned.h

But don't do that.  Better is to make the inclusion of banned.h a coding standard, and rely on code reviews to catch it.

If you are really insistent on enforcing this technically, you could have a custom build step that grep'd files for "banned.h" prior to compilation, failing the build if the line isn't found. (Or use some static analysis tool that tags deprecated functions.)  Doing so as part of the build keeps your code simpler, and more portable.


问:
Allow iteration of an internal vector without leaking the implementation
I have a class that represents a list of people.

```<code>class AddressBook
{
public:
  AddressBook();

private:
  std::vector<People> people;
}
</code>```

I want to allow clients to iterate over the vector of people. The first thought I had was simply:

```<code>std::vector<People> & getPeople { return people; }
</code>```

However, I do not want to leak the implementation details to the client. I may want to maintain certain invariants when the vector is modified, and I lose control over these invariants when I leak the implementation.

What's the best way to allow iteration without leaking the internals?

答:
allow iteration without leaking the internals is exactly what the iterator pattern promises. Of course that is mainly theory so here is a practical example:

```<code>class AddressBook
{
  using peoples_t = std::vector<People>;
public:
  using iterator = peoples_t::iterator;
  using const_iterator = peoples_t::const_iterator;

  AddressBook();

  iterator begin() { return people.begin(); }
  iterator end() { return people.end(); }
  const_iterator begin() const { return people.begin(); }
  const_iterator end() const { return people.end(); }
  const_iterator cbegin() const { return people.cbegin(); }
  const_iterator cend() const { return people.cend(); }

private:
  peoples_t people;
};
</code>```

You provide standard begin and end methods, just like sequences in the STL and implement them simply by forwarding to vector's method. This does leak some implementation detail namely that you're returning a vector iterator but no sane client should ever depend on that so it is imo not a concern. I've shown all overloads here but of course you can start by just providing the const version if clients should not be able to change any People entries. Using the standard naming has benefits: anyone reading the code immediately knows it provides 'standard' iteration and as such works with all common algorithms, range based for loops etc.

Body:
allow iteration without leaking the internals is exactly what the iterator pattern promises. Of course that is mainly theory so here is a practical example:

class AddressBook
{
  using peoples_t = std::vector<People>;
public:
  using iterator = peoples_t::iterator;
  using const_iterator = peoples_t::const_iterator;

  AddressBook();

  iterator begin() { return people.begin(); }
  iterator end() { return people.end(); }
  const_iterator begin() const { return people.begin(); }
  const_iterator end() const { return people.end(); }
  const_iterator cbegin() const { return people.cbegin(); }
  const_iterator cend() const { return people.cend(); }

private:
  peoples_t people;
};

You provide standard begin and end methods, just like sequences in the STL and implement them simply by forwarding to vector's method. This does leak some implementation detail namely that you're returning a vector iterator but no sane client should ever depend on that so it is imo not a concern. I've shown all overloads here but of course you can start by just providing the const version if clients should not be able to change any People entries. Using the standard naming has benefits: anyone reading the code immediately knows it provides 'standard' iteration and as such works with all common algorithms, range based for loops etc.


问:
Securing sensitive data from developers
I have an enterprise application running that uses both MySQL and MongoDB datastores. My development team all have SSH access to the machine in order to perform application releases, maintenance, etc.

I recently raised a risk in the business when users started storing highly sensitive data on the application that the developers have indirect access to this data which caused a bit of a storm, so I have now been mandated with securing the data so that it is not accessible.

To me this does not seem possible because if the application has access to the database then a developer with access to the machine and application source will always be able to access the data.

答:
MongoDB has limited security controls and depends on a secure environment. Binding to a specific ip and port (and ssl since 2.2), and a crude authentication, that's what it offers. MYSQL adds GRANT o ON db.t TO... Data at rest is not encrypted, and ssl is not used by default. Create a fence. Readonly access for developers to application related log files should be enough to debug. Automate the application lifecycle.

Ansible helped us automate standard operations (deploy, upgrade, restore) over many single-tennant environments while using distinct encrypted vaults to store sensitive environment variables such as hosts, ports, and credentials. If each vault can only be decrypted by different roles, and only on a bastion host, for logged operations, then auditability provides acceptable security. If you grant SSH, then please use selinux to avoid key tampering, use a bastion host with ldap/kerberos authentication for administration, and use sudo wisely.

Title: Securing sensitive data from developers


问:
Why are there no PUT and DELETE methods on HTML forms?
HTML4 / XHTML1 allows only GET and POST in forms, now it seems like HTML5 will do the same. There is a proposal to add these two but it doesn't seem to be gaining traction.

What were the technical or political reasons for not including PUT and DELETE in HTML5 specification draft?

答:
This is was raised in 2010 as Bug 10671
consider adding support for PUT and DELETE as form methods.

There was a moderate amount of pushback for this "feature" and some heavy-handedness but eventually this was escalated as two issues on the Working Groups bug tracker:

ISSUE-195: Enhance http request generation from forms

ISSUE-196: Define user agent http response handling behaviour

The issue ISSUE-196 resulted in a concensus decision to perform no change to the specification as the HTML specification does not currently restrict how responses to POST requests are handled. I believe this particular issue was raised in attempting to reconcile POST redirect patterns commonly in use and how ReSTful servers often provide 2xx responses with short messages rather than something useful to be rendered in a browser.

The issue ISSUE-195 was presented to the chairs. Cameron Jones stepped up to volunteer in writing a change proposal on the 18th of January 2012 which he submitted to become the first working draft on the 29th May 2014. The draft will go through the W3C recommendations process.

With any luck, this will soon become a W3C recommendation and implemented by browser vendors, and would be a great forward step in removing the blockers to produce unified, semantic and browser friendly ReSTful services. I imagine this will spark an interesting evolution in service patterns. There's a good talk by Jon Moore - Hypermedia APIs worth watching, this got my interest but fell down at the first hurdle (this one).

ContentLicense: CC BY-SA 4.0


问:
Why do we have to mention the data type of the variable in C
Usually in C, we have to tell the computer the type of data in variable declaration. E.g. in the following program, I want to print the sum of two floating point numbers X and Y.

```<code>#include<stdio.h>
main()
{
  float X=5.2;
  float Y=5.1;
  float Z;
  Z=Y+X;
  printf("%f",Z);

}
</code>```

I had to tell the compiler the type of variable X.

Can't the compiler determine the type of X on its own?

Yes, it can if I do this:

```<code>#define X 5.2
</code>```

I can now write my program without telling the compiler the type of X as:

```<code>#include<stdio.h>
#define X 5.2
main()
{
  float Y=5.1;
  float Z;
  Z=Y+X;
  printf("%f",Z);

}
</code>```

So we see that C language has some kind of feature, using which it can determine the type of data on its own. In my case it determined that X is of type float.

Why do we have to mention the type of data, when we declare something in main()? Why can't the compiler determine the data type of a variable on its own in main() as it does in #define.

答:
X in the second example is never a float.  It is called a macro, it replaces the defined macro value 'X' in the source with the value.  A readable article on #define is here.

In the case of the supplied code, before compilation the preprocessor changes the code

```<code>Z=Y+X;
</code>```

to

```<code>Z=Y+5.2;
</code>```

and that is what gets compiled.

That means you can also replace those 'values' with code like

```<code>#define X sqrt(Y)
</code>```

or even

```<code>#define X Y
</code>```

Body:
X in the second example is never a float.  It is called a macro, it replaces the defined macro value 'X' in the source with the value.  A readable article on #define is here.

In the case of the supplied code, before compilation the preprocessor changes the code

Z=Y+X;

to

Z=Y+5.2;

and that is what gets compiled.

That means you can also replace those 'values' with code like

#define X sqrt(Y)

or even

#define X Y


答:
You are comparing variable declarations to #defines, which is incorrect. With a #define, you create a mapping between an identifier and a snippet of source code. The C preprocessor will then literally substitute any occurrences of that identifier with the provided snippet. Writing

```<code>#define FOO 40 + 2
int foos = FOO + FOO * FOO;
</code>```

ends up being the same thing to the compiler as writing

```<code>int foos = 40 + 2 + 40 + 2 * 40 + 2;
</code>```

Think of it as automated copy&paste.

Also, normal variables can be reassigned, while a macro created with #define can not (although you can re-#define it). The expression FOO = 7 would be a compiler error, since we can't assign to “rvalues”: 40 + 2 = 7 is illegal.

So, why do we need types at all? Some languages apparently get rid of types, this is especially common in scripting languages. However, they usually have something called “dynamic typing” where variables don't have fixed types, but values have. While this is far more flexible, it's also less performant. C likes performance, so it has a very simple and efficient concept of variables:

There's a stretch of memory called the “stack”. Each local variable corresponds to an area on the stack. Now the question is how many bytes long does this area have to be? In C, each type has a well-defined size which you can query via sizeof(type). The compiler needs to know the type of each variable so that it can reserve the correct amount of space on the stack.

Why don't constants created with #define need a type annotation? They are not stored on the stack. Instead, #define creates reusable snippets of source code in a slightly more maintainable manner than copy&paste. Literals in the source code such as "foo" or 42.87 are stored by the compiler either inline as special instructions, or in a separate data section of the resulting binary.

However, literals do have types. A string literal is a char *. 42 is an int but can also be used for shorter types (narrowing conversion). 42.8 would be a double. If you have a literal and want it to have a different type (e.g. to make 42.8 a float, or 42 an unsigned long int), then you can use suffixes – a letter after the literal that changes how the compiler treats that literal. In our case, we might say 42.8f or 42ul.

Some languages have static typing as in C, but the type annotations are optional. Examples are ML, Haskell, Scala, C#, C++11, and Go. How does that work? Magic? No, this is called “type inference”. In C# and Go, the compiler looks at the right hand side of an assignment, and deduces the type of that. This is fairly straightforward if the right hand side is a literal such as 42ul. Then it's obvious what the type of the variable should be. Other languages also have more complex algorithms that take into account how a variable is used. E.g. if you do x/2, then x can't be a string but must have some numeric type.

Title: Why do we have to mention the data type of the variable in C

Body:
Usually in C, we have to tell the computer the type of data in variable declaration. E.g. in the following program, I want to print the sum of two floating point numbers X and Y.

```<code>#include<stdio.h>
main()
{
  float X=5.2;
  float Y=5.1;
  float Z;
  Z=Y+X;
  printf("%f",Z);

}
</code>```

I had to tell the compiler the type of variable X.

Can't the compiler determine the type of X on its own?

Yes, it can if I do this:

```<code>#define X 5.2
</code>```

I can now write my program without telling the compiler the type of X as:

```<code>#include<stdio.h>
#define X 5.2
main()
{
  float Y=5.1;
  float Z;
  Z=Y+X;
  printf("%f",Z);

}
</code>```

So we see that C language has some kind of feature, using which it can determine the type of data on its own. In my case it determined that X is of type float.

Why do we have to mention the type of data, when we declare something in main()? Why can't the compiler determine the data type of a variable on its own in main() as it does in #define.

Body:
You are comparing variable declarations to #defines, which is incorrect. With a #define, you create a mapping between an identifier and a snippet of source code. The C preprocessor will then literally substitute any occurrences of that identifier with the provided snippet. Writing

#define FOO 40 + 2
int foos = FOO + FOO * FOO;

ends up being the same thing to the compiler as writing

int foos = 40 + 2 + 40 + 2 * 40 + 2;

Think of it as automated copy&paste.

Also, normal variables can be reassigned, while a macro created with #define can not (although you can re-#define it). The expression FOO = 7 would be a compiler error, since we can't assign to “rvalues”: 40 + 2 = 7 is illegal.

So, why do we need types at all? Some languages apparently get rid of types, this is especially common in scripting languages. However, they usually have something called “dynamic typing” where variables don't have fixed types, but values have. While this is far more flexible, it's also less performant. C likes performance, so it has a very simple and efficient concept of variables:

There's a stretch of memory called the “stack”. Each local variable corresponds to an area on the stack. Now the question is how many bytes long does this area have to be? In C, each type has a well-defined size which you can query via sizeof(type). The compiler needs to know the type of each variable so that it can reserve the correct amount of space on the stack.

Why don't constants created with #define need a type annotation? They are not stored on the stack. Instead, #define creates reusable snippets of source code in a slightly more maintainable manner than copy&paste. Literals in the source code such as "foo" or 42.87 are stored by the compiler either inline as special instructions, or in a separate data section of the resulting binary.

However, literals do have types. A string literal is a char *. 42 is an int but can also be used for shorter types (narrowing conversion). 42.8 would be a double. If you have a literal and want it to have a different type (e.g. to make 42.8 a float, or 42 an unsigned long int), then you can use suffixes – a letter after the literal that changes how the compiler treats that literal. In our case, we might say 42.8f or 42ul.

Some languages have static typing as in C, but the type annotations are optional. Examples are ML, Haskell, Scala, C#, C++11, and Go. How does that work? Magic? No, this is called “type inference”. In C# and Go, the compiler looks at the right hand side of an assignment, and deduces the type of that. This is fairly straightforward if the right hand side is a literal such as 42ul. Then it's obvious what the type of the variable should be. Other languages also have more complex algorithms that take into account how a variable is used. E.g. if you do x/2, then x can't be a string but must have some numeric type.


答:
C doesn't have type inference (thats what it is called when a compiler guesses the type of a variable for you) because it is old. It was developed in the early 1970's

Many newer languages have systems that allow you to use variables without specifying their type (ruby, javascript, python, etc.)


问:
How do you keep your unit tests working when refactoring?
In another question, it was revealed that one of the pains with TDD is keeping the testing suite in sync with the codebase during and after refactoring.

Now, I'm a big fan of refactoring. I'm not going to give it up to do TDD. But I've also experienced the problems of tests written in such a way that minor refactoring leads to lots of test failures.

How do you avoid breaking tests when refactoring?

Do you write the tests 'better'? If so, what should you look for?

Do you avoid certain types of refactoring?

Are there test-refactoring tools?

Edit: I wrote a new question that asked what I meant to ask (but kept this one as an interesting variant).

答:
Contrary to the other answers, it is important to note that some ways of testing can become fragile when the system under test (SUT) is refactored, if the test is whitebox.

If I'm using a mocking framework that verifies the order of the methods called on the mocks (when the order is irrelevant because the calls are side-effect free); then if my code is cleaner with those method calls in a different order and I refactor, then my test will break.  In general, mocks can introduce fragility to tests.

If I am checking the internal state of my SUT by exposing its private or protected members (we could use "friend" in visual basic, or escalate the access level "internal" and use "internalsvisibleto" in c#; in many OO languages, including c# a "test-specific-subclass" could be used) then suddenly the internal state of the class will matter - you may be refactoring the class as a black box, but white box tests will fail.  Suppose a single field is reused to mean different things (not good practice!) when the SUT changes state - if we split it into two fields, we may need to rewrite broken tests.

Test-specific-subclasses can also be used to test protected methods - which may mean that a refactor from the point of view of production code is a breaking change from the point of view of test code.  Moving a few lines into or out of a protected method may have no production side effects, but break a test.

If I use "test hooks" or any other test-specific or conditional compilation code, it can be hard to ensure that tests don't break because of fragile dependencies on internal logic.

So to prevent tests from becoming coupled to the intimate internal details of the SUT it may help to:

Use stubs rather than mocks, where possible.  For more info see Fabio Periera's blog on tautological tests, and my blog on tautological tests.

If using mocks, avoid verifying the order of methods called, unless it is important.

Try to avoid verifying internal state of your SUT - use its external API if possible.

Try to avoid test-specific logic in production code

Try to avoid using test-specific subclasses.

All of the points above are examples of white-box coupling used in tests.  So to completely avoid refactoring breaking tests, use black-box testing of the SUT.

Disclaimer: For the purpose of discussing refactoring here, I am using the word a little more broadly to include changing internal implementation without any visible external effects.  Some purists may disagree and refer exclusively to Martin Fowler and Kent Beck's book Refactoring - which describes atomic refactoring operations.

In practice, we tend to take slightly larger non-breaking steps than the atomic operations described there, and in particular changes that leave the production code behaving identically from the outside may not leave tests passing.  But I think it is fair to include "substitute algorithm for another algorithm that has identical behaviour" as a refactor, and I think Fowler agrees.  Martin Fowler himself says that refactoring may break tests:

When you write a mockist test, you are testing the outbound calls of the SUT to ensure it talks properly to its suppliers. A classic test only cares about the final state - not how that state was derived. Mockist tests are thus more coupled to the implementation of a method. Changing the nature of calls to collaborators usually cause a mockist test to break.

[...]

Coupling to the implementation also interferes with refactoring, since
  implementation changes are much more likely to break tests than with
  classic testing.

Fowler - Mocks aren't stubs


问:
Distributing a set of "Jobs" across multiple computers
I'm rather new to distributed computing and would like some assistance with the overall architecture of my application.

My application has Jobs that can be added to a JobQueue. Then one or more JobRunner instances can be setup to run the jobs on the queue and generate JobResults. The JobResults will then be sent to some destination like a report, log file, email notification etc..

However, I also want to be able to group a related set of Jobs into a JobSet which in turn will be processed into a JobSetResult that contains all the corresponding JobResults. Each Job, however, will still be processed independently by a JobRunner. Once all the JobResults are collected the final JobResult will be sent to some destination like a log or email notification.

For example a user may create a set of jobs to process a list of files. They would create a JobSet containing a number of FileProcessingJobs and submit it to be run. I obviously don't want the user to get an email notification for every file, but only the final JobSetResult when the entire JobSet is complete.

I'm having trouble figuring out the best way to keep track of all this in a distributed environment. Is there some existing architectural design pattern which matches what I'm trying to do?

答:
I think that the solution to your problem is that you have a main thread that is handling certain aspects of your application and JobRunner threads that appear to be doing more business logic related processing.

If you are going to go parallel processing then don't dip your feet in the pool, jump right in and make any logic in your application a job.  Everything should be asynchronous including creating JobSet's and email processed results.

If you are familiar with Batch processing then this is like a massively parallel paradigm.  Each runner should have three distinct aspects.

Reader - Read in a chunk from a source or data store that a particular type of Runner should process.

Processor - Process that chunk of data with logic

Writer - Persist your finished result to be picked up later by a future chunk.

If you design your runners correctly then they can constantly be running and looking for more chunks to read in, process ad-hoc and write for another type of Runner to pick up with its Reader.

There are frameworks that assist with this kind of application development, Apache Hadoop.  It builds this infrastructure for you so you can focus on design and business logic instead of boilerplate code.


问:
Going from cutting edge to maintaining legacy projects
I have an Access 03 program with a bunch of VBA code that is in use and the end user wants new functionality. I am finding it very difficult to add new functionality because my brain wants to use the most recent .NET technologies and VBA is not recent at all.

How should I go about "rolling back" technologies in my head to keep my frustration levels to a minimum?

Also my boss said it wasn't in the budget to rewrite the project from access and vba to some sort of form and SQL combo (which I could probably pound out in a few days, which is the same amount of time that I feel that it will take me to look up and implement in the old system).

答: Apart from imagining that you are in year 1997 and just getting your hands dirty with VBA, I don't see any other way you could fix this.</p>

ContentLicense: CC BY-SA 2.5


问:
What is the difference between a Future and a Promise?
What is the difference between a Future and a promise? (In Akka and Gpars.)

They look the same to me as both block and return the value of the future when get is called and a promise is to get the result of a future.

答:
I'll add a bit here because I have been working with a plethora of Futures in Java as of late but have a background in Scala/Akka development as well. This answer will mostly duplicate what has been said but will point out the plethora of implementations in popular use today on the JVM.

First, original poster mentions using get and blocking - please never ever do this outside of tests.

When I teach FP and Concurrency concepts in my current role, I first tell the student that semantically promises and futures are synonyms because as a consumer of a promise or a future api, the developer does not need to understand that there are or IF there are semantic differences - only the mechanics for handling them without blocking IO.

To say that a future can't be completed and that a promise can (eg as per scala/akka/play apis for example) is too simplistic:

Some Futures can be completed
Java8 now introduces a CompletableFuture into the standard library.

Some Promises can't be completed
Similarly, in the Play promise API a Promise can't be fulfilled but a RedeemablePromise can so play introduces a different semantic - even while being under the Typesafe umbrella. Further, Play promise API can convert with scala futures in both directions -  (F.Promise.wrap(future) or promise.wrapped()).

Working with Typesafe technology on Java8 you will often go back and forth between futures/promises simply because one API is preferable (Play Promise API seems better with Java8 lambdas). On Akka+Play+Java8 you will be taking futures from Actors and wrapping them into promises, composing callbacks, and returning that from the controller.

So, as I tell people when I teach, Promises and Futures are more or less synonyms.


问:
Should I do a different SQL table for user privacy settings or just keep it at the users table?
So I am developing a Web Application and I have some concerns about the database. I use a lot of boolean settings at the user table with the form privacy_allow_1, privacy_allow_that, privacy_allow_this etc etc.

As they keep stacking would it be just better to use a different table just for the privacy settings and link it to the users?

What are the prons and cons between the two options?

答:
Create another table with a schema similar to

```<code>userid
PrivacyTypeId
allowed
</code>```

and

```<code>PrivacyTypeId
PrivacyType
</code>```

This structure will allow you to add\remove\deactivate permissions without any DDL changes

Body:
Create another table with a schema similar to

userid
PrivacyTypeId
allowed

and

PrivacyTypeId
PrivacyType

This structure will allow you to add\remove\deactivate permissions without any DDL changes


答:
Your choice of framework will decide the exact API, but what you are looking to do is a fairly common task.

You need a concept of a JobSet.  Some frameworks will provide you such a concept for you.  I would concentrate on choosing your framework first, and researching how that framework will do what you want.  What you want is a very common desire, so it should be supported by any reasonable framework.

But, if for some reason, you choose a framework that doesn't do it for you...

If your chosen framework does not do this for you, you will have to maintain a text file with all of the jobs in your JobSet (populate it as you submit the jobs).  Whenever a job completes, it opens the file and removes itself from the list of pending jobs.  If it is the last job within a JobSet, it then runs the "gather" script before actually finishing.

Title: Distributing a set of "Jobs" across multiple computers

Body:
I'm rather new to distributed computing and would like some assistance with the overall architecture of my application.

My application has Jobs that can be added to a JobQueue. Then one or more JobRunner instances can be setup to run the jobs on the queue and generate JobResults. The JobResults will then be sent to some destination like a report, log file, email notification etc..

However, I also want to be able to group a related set of Jobs into a JobSet which in turn will be processed into a JobSetResult that contains all the corresponding JobResults. Each Job, however, will still be processed independently by a JobRunner. Once all the JobResults are collected the final JobResult will be sent to some destination like a log or email notification.

For example a user may create a set of jobs to process a list of files. They would create a JobSet containing a number of FileProcessingJobs and submit it to be run. I obviously don't want the user to get an email notification for every file, but only the final JobSetResult when the entire JobSet is complete.

I'm having trouble figuring out the best way to keep track of all this in a distributed environment. Is there some existing architectural design pattern which matches what I'm trying to do?


问:
Improve the speed of a Tomcat Server with MySQL
I'm developing an application with 3 sides, desktop (JavaFX), server (Tomcat) and Android.

And a MySQL Database Server.

The app receive mails and convert them into tasks. The tasks are sent to the android devices from the desktop app. The user of the Android device do stuff with the task and send the task with new information to the server.

The desktop app takes the data from the database.

Now it's working, but goes too slowly from the desktop side, due to the server possibly having a big payload.

The server has 3 tasks:

JavaMail email reader, and write in the database.

Send PUSH messages to the Android devices and receive some information from them, and write in the database.

Receive the GPS position from the Android devices, and write it in the database.

My doubts are:

A)Separate the server side in 3 projects.

Mail reader

Send PUSH to the Android devices.

GPS position receptor.

B)Separate the database in 2 databases:

For the GPS position.

For the info of the tasks.

This steps will make the app faster?

Edit to answer  Clinton Bosch:

I´m using Hibernate to connect to the database, here is my hibernate config file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <property name="hibernate.c3p0.min_size">2</property>
        <property name="hibernate.c3p0.max_size">150</property>
        <property name="hibernate.c3p0.timeout">100</property>
        <property name="hibernate.c3p0.max_statements">0</property>

        <property name='connection.username'>root</property>

        <!-- Database connection settings -->
        <property name='connection.driver_class'>com.mysql.jdbc.Driver</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name='connection.pool_size'>10</property>

        <!-- SQL dialect -->
        <property name='dialect'>org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name='show_sql'>false</property>

        <!-- Mapping files -->
    </session-factory>
</hibernate-configuration>
</code>```

答:
Are you using a connection pool? very often I have seen developers using an application server without a connection pool and the majority of the time is spent establishing DB connections which are very heavy processes.

Apart from that using a profiler like jprofiler (for which you can get an eval license) would be your best port of call to diagnose your problem.

Microservices (separate servers) is quite a popular architecture especially in large scale applications because a failure in a single part of it does not mean everything stops (one of many reasons to use this architecture). The negative is that it does require more resources (one of many reasons not to use this architecture).

That being said, tomcat is a very powerful application server and I am running it with enterprise applications serving thousands of requests per minute without issue.

It is difficult to advise without having the full picture wrt size etc, but I would start by profiling.


问:
Early destruction of objects in c++
I am not sure if this is the right forum of this question, but I will try here since this question about the c++ language. The problem:

I use one global variable in my code which is a graphics object. The thing is that when I shut down the program I tried to delete all the created objects (in a function called close, since I wanted to finish some processes from an C API as well). However, when I deleted that global graphics object I got a memory access violation error at the end of main. The reason for this was that the destructor was called again when main ended. This was something that I was not aware of. This led me to the for this program completely irrelevant (since I still wanted to keep the variable until the GUI closed), but for c++ programming really relevant question; Is it impossible to destroy a global c++ object before the end of main?

However, I read this

Static: Objects declared in global or namespace scope (§6.3.4) and statics declared in func- tions (§12.1.8) or classes (§16.2.12) are created and initialized once (only) and ‘‘live’’ until the program terminates (§15.4.3). Such objects are called static objects. A static object has the same address throughout the life of a program execution. Static objects can cause serious problems in a multi-threaded program because they are shared among all threads and typically require locking to avoid data races (§5.3.1, §42.3)

However, though versions of this text appear all over on the internet my question is not completely answered by this explanation. Though it may be implied, since global variables always seem to be static it would be nice to have a straight out answer.

答:
This is a simple C++ rule: objects that are more complex that a simple integer, pointer, etc (not a native type) have constructors and destructors. When an instance of such object is declared by value inside a scope, its constructor gets automatically called. When the scope it was declared is exited, the destructor gets automatically called. So take this example:

```<code>// Constructor gets called now, which is before 'main()'
// enters for a global object like this one.
GraphicsObject graphics;

int main()
{
    // Do stuff with 'graphics'
    // ...

} // When we get here, at the end of main, the destructor of 'graphics' is called.
</code>```

There's no way do change this behaviour, but you can work around it if you need more control over the lifetime of an object. One way is to use pointers. In the following example, I'm going to use a raw pointer for simplicity. You should not adopt this approach though. Always prefer a smart pointer for that.

```<code>// Allocated dynamically with 'new'. Constructor still called here, before 'main()' enters.
// Destructor will not be called until you 'delete' it yourself.
GraphicsObject * graphics = new GraphicsObject;

int main()
{
    // Do stuff with 'graphics'
    // ...

    // 'graphics' destructor only gets called now because we have explicitly
    // deleted it. If we didn't delete the dynamic object, the destructor
    // would never be called. Not deleting would qualify as a "memory leak", BTW.
    delete graphics;
}
</code>```

Using a pointer, instead of a declaration by value, is the default way of extending the lifetime of an object beyond its scope. In your particular case, however, I suspect the problem could be resolved in a simpler way by introducing a cleanup() method in your graphics object that you call at the end of main(). Make sure that cleanup() frees all associated resources but leaves the object in a state where the destructor can still function when called automatically at the end of main().

Also, it seems that you are trying to implementing the Singleton Pattern, which can be implemented in several different ways. Do an internet search about it and you might find other singleton setups that better fit your needs.

Title: Early destruction of objects in c++

Body:
This is a simple C++ rule: objects that are more complex that a simple integer, pointer, etc (not a native type) have constructors and destructors. When an instance of such object is declared by value inside a scope, its constructor gets automatically called. When the scope it was declared is exited, the destructor gets automatically called. So take this example:

// Constructor gets called now, which is before 'main()'
// enters for a global object like this one.
GraphicsObject graphics;

int main()
{
    // Do stuff with 'graphics'
    // ...

} // When we get here, at the end of main, the destructor of 'graphics' is called.

There's no way do change this behaviour, but you can work around it if you need more control over the lifetime of an object. One way is to use pointers. In the following example, I'm going to use a raw pointer for simplicity. You should not adopt this approach though. Always prefer a smart pointer for that.

// Allocated dynamically with 'new'. Constructor still called here, before 'main()' enters.
// Destructor will not be called until you 'delete' it yourself.
GraphicsObject * graphics = new GraphicsObject;

int main()
{
    // Do stuff with 'graphics'
    // ...

    // 'graphics' destructor only gets called now because we have explicitly
    // deleted it. If we didn't delete the dynamic object, the destructor
    // would never be called. Not deleting would qualify as a "memory leak", BTW.
    delete graphics;
}

Using a pointer, instead of a declaration by value, is the default way of extending the lifetime of an object beyond its scope. In your particular case, however, I suspect the problem could be resolved in a simpler way by introducing a cleanup() method in your graphics object that you call at the end of main(). Make sure that cleanup() frees all associated resources but leaves the object in a state where the destructor can still function when called automatically at the end of main().

Also, it seems that you are trying to implementing the Singleton Pattern, which can be implemented in several different ways. Do an internet search about it and you might find other singleton setups that better fit your needs.


答:
The example is kinda messed up, and looks to me like it just hasn't been thought through.

Currencies aren't like scientific measurements, you shouldn't implicitly convert between them on demand. The value of a currency will change on the day. You should really only convert between currencies with the end-users explicit permission, certainly not implicitly all over the place.

The class holds money as a double. DON'T EVER DO THAT. See What every computer scientist should know about floating point. Money should always be held in an integral or decimal type. If you use double you'll get rounding errors and people get really unhappy if you round their money wrong.

As it stands, there is a circular dependency between Money and Currency. Money contains a currency, but currency also works with money. That's not necessarily wrong, but is suspect.

The line in question:

```<code>m=currency.convertToYourCurrency(m)
</code>```

You are correct. As written, it would require a getter or something similiar. Instead, it should be

```<code>m = m.convertToCurrency(currency)
</code>```

Where convertToCurrency is defined

```<code>Money convertToCurrency(Currency currency) {
   return new Money(currency, this.currency.convertTo(currency, this.value));
}
</code>```

Title: Getters and Setters unclear example

Body:
The example is kinda messed up, and looks to me like it just hasn't been thought through.

Currencies aren't like scientific measurements, you shouldn't implicitly convert between them on demand. The value of a currency will change on the day. You should really only convert between currencies with the end-users explicit permission, certainly not implicitly all over the place.

The class holds money as a double. DON'T EVER DO THAT. See What every computer scientist should know about floating point. Money should always be held in an integral or decimal type. If you use double you'll get rounding errors and people get really unhappy if you round their money wrong.

As it stands, there is a circular dependency between Money and Currency. Money contains a currency, but currency also works with money. That's not necessarily wrong, but is suspect.

The line in question:

m=currency.convertToYourCurrency(m)

You are correct. As written, it would require a getter or something similiar. Instead, it should be

m = m.convertToCurrency(currency)

Where convertToCurrency is defined

Money convertToCurrency(Currency currency) {
   return new Money(currency, this.currency.convertTo(currency, this.value));
}


问:
What are the advantages of continuous deployment?
Continuous deployment require a lot of effort, beyond what is needed for continuous integration.

Since every change corresponds to a release (more or less), there is far less time and resources available for manual testing. They need to be almost entirely replaced by automated tests, which in some cases can be very difficult to do well, and can require extensive development of automated tools. (CI encourages this too. But in CD it becomes absolutely essential, and mistakes are much more damaging.)

Since deployments are far more frequent, there is much less allowable downtime or disruption during a deployment. It requires better automated architecture management and deployment strategies.

Continuous deployment is popular, so clearly there are some great benefits to offset these costs.

What are the advantages of continuous deployment?

(Specifically, I am curious about benefits unique to continuous deployment, that wouldn't be obtained by continuous integration alone.)

答:
Continuous deployment or continuous delivery is very common in web services and SaaS apps. Amazon, Facebook, Github, Google...they're all deploying all the time. Some operators deploy a handful or even dozens of updates a day for each very narrowly-defined service. I'm not even sure you could easily count the number of deployment events massive shops like Amazon and Google have, per day, in aggregate across their entire estate.

Why do it that way?

Users have fixes, updates, improvements, and new features in their hands early and often. The "patch" and upgrade cycles are integrated into everyday use, not spaced out in major releases.

Internal managers (product owners for individual lines of business, marketing campaigns, etc.) see their projects decoupled from all the other projects in the organization, therefore are ready to be presented to customers immediately as they are ready, not dependent on numerous other variables or "release trains."

There is less "dump a lot of new features, fixes, etc. all in one shot" phenomenon. Both users and support teams learn to hate "release day" when it's periodic, because that's when the most bugs, new breakage, unknown new features/behaviors, etc. manifest themselves. Continuous deployment spreads those release moments out in many, very small chunks. (That may have its own drawbacks, but the pain is more evenly spread.)

For agility. Agile techniques of all kinds require feedback loops from users. If you have a few main stakeholders, you can ask them "What do you think of this idea?" How would Amazon do that? Hold the world's largest focus group? No, they publish and go. They get feedback based on how things go, based on detailed analytics rather than direct customer feedback. Content-heavy organizations seem especially likely to become eager, active publishers with analytics-based feedback loops.

For A/B testing or its multivariate equivalents. It's hard to manage complex businesses with thousands or millions of products, product options, and product possibilities "by the seat of your pants.". They need to be data driven. While related to the previous point about feedback loops, continuous delivery makes the room necessary to be continuously testing multiple options in the real-world laboratory of customer behavior. Without the ability to constantly deliver and measure changes, there would be much less opportunity to test different hypotheses and options, and thus much less opportunity to gather valuable business analytics.

Fighting the nightmare of "version drift." Those running Web-facing services and apps get pretty good at slipstreaming and managing version drift--situations where there may be multiple logical versions of an app simultaneously in use. But even those good at running a dozen or two different versions don't want there to be 200, 2,000, or 20,000 different version configurations extant. The configuration management hassles and support costs become too great. Constantly deploying new code (and retiring old versions) keeps the number of actually-in-use versions to a dull roar.

Build best practices and organizational fitness. Just like when you introduce automated testing techniques or continuous integration, it isn't a simple change. You don't just do a dab here and there. You have to commit to the idea of testing, or testing everything. You have to get good at it, be disciplined about it, and make sure you have the right tools, environment, and culture to become efficient and effective at that style of operation. Web properties, by virtue of their massive customer bases and constant need for new content, new services, and patches/updates to be deployed, not only have to do a huge number of updates, they have to get really good at always updating things. That leads shops like Netflix to make a continuous "build-bake-deploy" cycle part of their people and their process--not just a technical feature, but part-and-parcel of their development and operations culture.

While continuous deployment is popular in Internet-faced apps, nothing is ever perfectly continuous. There are always internal services, capacity moves, organizational readiness, and other infrastructure changes that can delay or be a prerequisite of various releases. Even for services for which many updates are continuously delivered, for technical, marketing, training, and support purposes, when there are "big" changes, it's still convenient to present, promote, train, and deploy those as a bundle.

Some changes change the nature or interface of an app. It's not wise to have that look and work one way one minute, then have it work and look different on the next page reload or AJAX call. Some features or elements only make sense in the context of having other features available. Finally, many big changes require different backend services to be assembled, or different data schema. These are all situations in which always deploying continuously doesn't make sense. Limiting the number of "major versions" in play can help users consume, and operators effectively deliver, the service. So even in the most aggressive cases, it's "continuous with occasional bumps."


问:
We'd like to release only the services that have changed, in a continuous delivery context. How would we do that?
I am new to continuous delivery, so please help me understand if my ideas are incorrect, I have XY problems, etc..

My organization runs web services, with services-oriented architecture. Currently, we have about a dozen services. Naturally, these services share some code in common. To date, we've done batched releases every 2 weeks. We want to move to CD

We don't want to deploy every single service for every single change. It can be unnecessarily disruptive, time-consuming, and it isn't scalable. So we'd like to release only the services that have changed. This also applies to common code. So if service A and B have project C's code in common, and C changes, we'd like to release A and B.

Does this sound like a reasonable idea of what continuous integration would look like?

Are there any tools/processes that help in deploying only the minimal amount of changes for changed code?

It seems like large organizations like Google and Facebook that use continuous delivery have these same needs, though I haven't discovered how they do it. (My problem isn't nearly at that sort of scale, but the basic problem seems similar.)

答:
Well, to my understanding, you already have your answer.
Replace "common code" to "common business rules" and it becomes obvious. If the behaviors of both services A and B have changed, you have to redeploy both A and B.

However, I think this situation smells familiar... Do you have "common code" for things that aren't really common business rules? If you do, you're in for some surprises.

I may just be straying from the topic here, but I've seen this happen before. Quite often, people see two similar blocks of code and think "Hey, I've seen this before... A for-loop at a collection of Orders, filtering by isSubmitted... Yep, just like in that other component. I think I can extract that into a common object!". This is soon followed by a "Hey guys, look, I've just removed some duplication!" (I may or may not be quoting myself here...).

What happens next is surprising: One component changes that behavior, while the other doesn't. Then you go to the "common component" and try to slice into smaller "reusable pieces", trying to keep it as common, but different for each dependent component. This happens for a while, until people finally realize that the code shouldn't really belong there.

Turns out this is a often the result of following DRY and "remove duplication", without considering that, in a more abstract level, there really isn't duplication in the two very similar blocks of code. Now, I'm not saying DRY and "remove duplication" are bad at all, but that you must also pay attention to the Single Responsibility Principle.

Sometimes, two identical blocks of code serve different roles in the system, and just accidentally happen to do the same thing. But since the roles are different, the requirements for a role may change while the other doesn't. I recommend watching this talk about the SRP, where that same example is given.

It may look like I've strayed too far off from the topic here, but SRP is very closely related to continuous delivery, exactly because it aims at reducing the amount of accidental coupling between modules (and services), allowing changes to be kept at a minimum range of impact, to a point where only one module has to be redeployed.

But hey, I may really just have strayed off, and you really just have common business behavior between your services. If that's the case, as I said before, you already have your answer. Anything that changes get redeployed, and you won't have to find new tools for that, since this should be obvious, because you also need to test those services.


问:
Efficiency of C# dictionaries
C# dictionaries are a simple way to find if something exists etc etc. I have a question though on how they work. Let's say instead of a dictionary I use an ArrayList. Instead of using ContainsKey (or an equivalent method in another language) I loop through the ArrayList to check if something exists there (or performing binary search if data is sorted or something similar). What's the difference in efficiency? Is the ContainsKey method using some more efficient way rather than looping through the keys and check if what I am searching exists?

If let's say I had created a specific hash function which corresponds to the type of data that I am having and is specifically designed for that set of data then yes, that hash function is indeed faster than looping through data. But dictionaries are general. ContainsKey method is not specific to the data that it gets, it's a general searching method.

Basically what I am asking is. Dictionaries are helpful to programmers. They include methods that help with many things and they combine strings with integers,(keys and values) and many more. But concerning efficiency, what do they offer? What's the difference in having a dictionary vs an ArrayList of structs(string,int)

答:
You've got to dig a bit to see how the Dictionary is implemented in C# - Its not as obvious as HashMap (a hash table) or TreeMap (a sorted tree) (or ConcurrentSkipListMap - a skip list).

If you dig down into the "Remarks" section:

The Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.

And there we have it.  It's a hash table. Note that I've linked the Wikipedia article there - its a fairly good read.  You may wish to read the section on collision resolution.  It is possible to get a pathological data set where the lookup devolves to O(N) (for example everything you insert falls to the same hash value or index in the hash table for some reason and you're left with linear probing).

While the Dictionary is a general purpose solution you shouldn't be passing around concrete types (such as the Dictionary) - you should be passing around the interfaces.  In this case, that interface is IDictionary (docs).  To this, you are perfectly capable of writing your own dictionary implementation that does things optimally for the data you have.

As to the efficiency of various lookup/contains?

Walking an unsorted list: O(N)

Binary search of a sorted array: O(log N)

Sorted tree: O(log N)

Hash table: O(1)

For most people, the hash table is what they want.

You may find that the SortedDictionary is what you want instead:

The SortedDictionary<TKey, TValue> generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this respect, it is similar to the SortedList<TKey, TValue> generic class. The two classes have similar object models, and both have O(log n) retrieval.

Though, again, if the data structure isn't one that works with your data ideally, you are given the tools (the interfaces) to be able to write one that works best for your data.

The dictionary itself is an abstract data type.  You give me a Dictionary and I know what i can do with it and all the tools there there for me to use by the nature of it being a Dictionary.  If you gave me an ArrayList, I would find myself writing my own code for searching, inserting, or deleting items from the list.  This wastes my time and also means that there's more likelihood for a bug as I copy the code again and again from spot to spot.

Title: Efficiency of C# dictionaries


答: Consider it an exercise in mental flexibility. Appreciate the chance to temporarily lower your standards, so when you come back to the most recent .net, it will be like paradise to you.</p>

Title: Going from cutting edge to maintaining legacy projects

Body:
I have an Access 03 program with a bunch of VBA code that is in use and the end user wants new functionality. I am finding it very difficult to add new functionality because my brain wants to use the most recent .NET technologies and VBA is not recent at all.

How should I go about "rolling back" technologies in my head to keep my frustration levels to a minimum?

Also my boss said it wasn't in the budget to rewrite the project from access and vba to some sort of form and SQL combo (which I could probably pound out in a few days, which is the same amount of time that I feel that it will take me to look up and implement in the old system).


问:
XSLT equivalent for JSON
I was interested in finding (or if necessary developing) an XSLT equivalent for JSON.

As I have not found any, I was considering the possible query language to use for matching JSON paths so as to apply templates (from JavaScript) when there was a match (probably just checking an array of matching patterns in order, and stopping at the first template which matches, though allowing for the equivalent of xsl:apply-templates to keep templates going for children).

I am aware of JSONPath, JSONQuery, and RQL as JSON query languages (though I was not fully clear on whether RQL supported absolute and relative paths). Any suggestions on factors to consider and relative advantages of each toward such a usage.

答:
While Jonathan largely talks about the nature of XSLT as a language in his answer, I think there's another angle to consider.

The purpose of XSLT was to transform XML documents into some other document (XML, HTML, SGML, PDF, etc). In this way, XSLT is frequently used, effectively, as a template language.

There is a vast array of template libraries out there, even if you restrict yourself to JavaScript libraries (which you shouldn't need to, since the JS in JSON only refers to the genesis of the notation and should not be taken to imply that JSON is only for JavaScript). This template engine selector gives and indication of the variety of JS options there are out there.

The latter half of your questions talks more about query languages and the XML version of these would be XPath (not XSLT). As you noted, there are a variety of options there and I don't anything to add to that list. This area is relatively new, so I'd suggest you pick one and just go with it.

Title: XSLT equivalent for JSON


问:
The term "aggregate" in GPL3
What does this part of GPL3 mean in simpler or more readable terms?

If I decide to enhance a GPL3 Program in which some snippets of the codes I could add are generic (may it be on a separate file or as part of a GPL-licensed file) and could be applied to other future softwares as well, would I be free to have it (the generic code) licensed in any way I want?  I'm still the original author of it after all.  Or would this need that I create a "landmark" software first that contains it just to show that it is originally a part of an "aggregate"?  Pardon if I didn't get things right and if what I'm asking is not even applicable.  Thanks.

A compilation of a covered work with other separate and independent
  works, which are not by their nature extensions of the covered work,
  and which are not combined with it such as to form a larger program,
  in or on a volume of a storage or distribution medium, is called an
  “aggregate” if the compilation and its resulting copyright are not
  used to limit the access or legal rights of the compilation's users
  beyond what the individual works permit. Inclusion of a covered work
  in an aggregate does not cause this License to apply to the other
  parts of the aggregate.

Reference: http://www.gnu.org/copyleft/gpl.html

答:
An aggregate is a collection of programs that are not collectively bound by the GPL.  In other words, they are not a collective work.  A collective work is bound by the GPL because the individual programs or modules form a collective whole.  An aggregate is not bound by the GPL because

The individual programs, if they communicate with each other, do so at "arms-length" (through mechanisms such as pipes), rather than through Application Programming Interfaces (especially early-bound ones).

The individual programs are capable of operating independently; that is, they are still fully functional if you remove the other programs from the aggregate.

An example of an aggregate would be a distribution disk containing several programs, each having its own software license.  Linux distributions (containing several programs and utilities, in addition to the operating system kernel) are considered aggregates.

In other words, having one GPL'd program on a disk or other storage medium with other unrelated programs does not cause those other unrelated programs to be bound by the GPL.  Simply copying a bunch of programs to a disk does not create what the GPL calls a "collective work."

Title: The term "aggregate" in GPL3


答: In two financial firms, developers did not have access to production machines. All requests to modify production machines had to go through an approval process, with a script, and was approved by managers. The dev-ops team completed the actual deployments. I assume this team was employees only, and passed background checks. They also did not have developer knowledge so probably couldn't snoop if they wanted to. In addition to this, you would encrypt all database entries using a secret key stored in the environment variables. Even if the databases leaked publicly no one could read it. This key can be further password protected (PBKDF) so only an executive can unlock it. Your system could require the executive password upon boot (or more likely delegated to dev-ops or a dev-ops manager). Basically the strategy is to disperse the knowledge so a critical mass of required knowledge does not exist in one person and there are checks-and-balances. This is how Coca-Cola protects its formula. Honestly, some of these answers are cop-outs.</p>

Title: Securing sensitive data from developers

Body:
I have an enterprise application running that uses both MySQL and MongoDB datastores. My development team all have SSH access to the machine in order to perform application releases, maintenance, etc.

I recently raised a risk in the business when users started storing highly sensitive data on the application that the developers have indirect access to this data which caused a bit of a storm, so I have now been mandated with securing the data so that it is not accessible.

To me this does not seem possible because if the application has access to the database then a developer with access to the machine and application source will always be able to access the data.


问:
Why is the hashCode method usage of HashSet not specified in the API?
I was trying to debug my code which uses a HashSet and searching through the SO, I found out that I needed to override the hashCode method as well. The strange part is, checking the related API, I did not see any part in it mentioning about the hashCode method. Quoting the definition of the add method of HashSet as seen in the API:

public boolean add(E e)

Adds the specified element to this set if it is not already present.
  More formally, adds the specified element e to this set if this set
  contains no element e2 such that (e==null ? e2==null : e.equals(e2)).
  If this set already contains the element, the call leaves the set
  unchanged and returns false.

Now in the quotation above, I don't see anywhere that mentions about the hashCode method. Shouldn't the correct statement have been like:

... if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)) AND if this set contains no element e2 such that (e==null ? e2==null : e.hashCode() == e2.hashCode()).

Now if you say that: "If o1.equals(o2) returns true, o1.hashCode() == o2.hashCode() MUST evaluate to true as well.", then I would ask three questions:

Where is that fact specified? (in general, or in the API)

Even if that fact is specified somewhere, where in the API it is specified that HashSet makes use of the hashCode method?

If that fact is indeed correct, why isn't the compiler enforces overriding the hashCode method, whenever the equals method is overridden?

答:
in the documentation of hashcode itself:

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

The general contract of hashCode is:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently
return the same integer, provided no information used in equals
comparisons on the object is modified. This integer need not remain
consistent from one execution of an application to another execution
of the same application.

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must
produce the same integer result.

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method
on each of the two objects must produce distinct integer results.
However, the programmer should be aware that producing distinct
integer results for unequal objects may improve the performance of
hash tables.

not that I can find, but hashcode is specifically there for the support of hash tables as said in the documentation.


答: You should be able to take satisfaction and professional pride in figuring out the existing code base, adding your new functionality in a way that doesn't make the situations worse, and not breaking the existing functionality.  I have to do this all the time, back and forth between recent technology and old technology.  I've always taken satisfaction out of being able to do this well.  </p>


答:
The specifics of the hashCode in the API is a few steps deep from HashSet:

HashSet See also -> HashMap ("This class implements the Set interface, backed by a hash table (actually a HashMap instance).")

HashMap See also: -> Object.hashCode()

Object#hashCode()

There, it reads:

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

The compiler doesn't know or care about the relationships between objects or methods.  On the other hand, there are several static analysis tools that do care:

Findbugs Class defines equals() but not hashCode():

This class overrides equals(Object), but does not override hashCode().  Therefore, the class may violate the invariant that equal objects must have equal hashcodes.

Findbugs Class defines equals() and uses Object.hashCode()

This class overrides equals(Object), but does not override hashCode(), and inherits the implementation of hashCode() from java.lang.Object (which returns the identity hash code, an arbitrary value assigned to the object by the VM).  Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes.

If you don't think instances of this class will ever be inserted into a HashMap/HashTable, the recommended hashCode implementation to use is:

```<code>public int hashCode() {
    assert false : "hashCode not designed";
    return 42; // any arbitrary constant will do
}
</code>```

PMD OverrideBothEqualsAndHashcode

Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass.

CheckStyle EqualsHashCode

Checks that classes that override equals() also override hashCode().

Rationale: The contract of equals() and hashCode() requires that equal objects have the same hashCode. Therefore, whenever you override equals() you must override hashCode() to ensure that your class can be used in hash-based collections.

Some IDEs may also have built in static analysis tools or generators to create equals and hashcode - sometimes as part of the same step (these are the fields of interest - poof there's the code).

Title: Why is the hashCode method usage of HashSet not specified in the API?

Body:
I was trying to debug my code which uses a HashSet and searching through the SO, I found out that I needed to override the hashCode method as well. The strange part is, checking the related API, I did not see any part in it mentioning about the hashCode method. Quoting the definition of the add method of HashSet as seen in the API:

public boolean add(E e)

Adds the specified element to this set if it is not already present.
  More formally, adds the specified element e to this set if this set
  contains no element e2 such that (e==null ? e2==null : e.equals(e2)).
  If this set already contains the element, the call leaves the set
  unchanged and returns false.

Now in the quotation above, I don't see anywhere that mentions about the hashCode method. Shouldn't the correct statement have been like:

... if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)) AND if this set contains no element e2 such that (e==null ? e2==null : e.hashCode() == e2.hashCode()).

Now if you say that: "If o1.equals(o2) returns true, o1.hashCode() == o2.hashCode() MUST evaluate to true as well.", then I would ask three questions:

Where is that fact specified? (in general, or in the API)

Even if that fact is specified somewhere, where in the API it is specified that HashSet makes use of the hashCode method?

If that fact is indeed correct, why isn't the compiler enforces overriding the hashCode method, whenever the equals method is overridden?

Body:
The specifics of the hashCode in the API is a few steps deep from HashSet:

HashSet See also -> HashMap ("This class implements the Set interface, backed by a hash table (actually a HashMap instance).")

HashMap See also: -> Object.hashCode()

Object#hashCode()

There, it reads:

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

The compiler doesn't know or care about the relationships between objects or methods.  On the other hand, there are several static analysis tools that do care:

Findbugs Class defines equals() but not hashCode():

This class overrides equals(Object), but does not override hashCode().  Therefore, the class may violate the invariant that equal objects must have equal hashcodes.

Findbugs Class defines equals() and uses Object.hashCode()

This class overrides equals(Object), but does not override hashCode(), and inherits the implementation of hashCode() from java.lang.Object (which returns the identity hash code, an arbitrary value assigned to the object by the VM).  Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes.

If you don't think instances of this class will ever be inserted into a HashMap/HashTable, the recommended hashCode implementation to use is:

public int hashCode() {
    assert false : "hashCode not designed";
    return 42; // any arbitrary constant will do
}

PMD OverrideBothEqualsAndHashcode

Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass.

CheckStyle EqualsHashCode

Checks that classes that override equals() also override hashCode().

Rationale: The contract of equals() and hashCode() requires that equal objects have the same hashCode. Therefore, whenever you override equals() you must override hashCode() to ensure that your class can be used in hash-based collections.

Some IDEs may also have built in static analysis tools or generators to create equals and hashcode - sometimes as part of the same step (these are the fields of interest - poof there's the code).


问:
How to make a website be formatted correctly on all screen sizes?
I recently made a pure (didn't use Bootstrap or anything else) HTML 'website' (didn't actually give it a url) on my laptop, but when I opened the website on my desktop, it looked horrible and nothing was formatted correctly (elements were too small, margins were too big or too small, etc.). What should I do to make sure my website fits on all screen sizes?</p>

答:
After re-reading your question you said it was pure HTML website. HTML is NOT where you want to do the design things, that should be done in another language (CSS3). HTML defines the content of what you want on your website, in the other hand you'll use CSS for placing, colouring, scaling and overall appearance.

From just your explanation there can be a lot of things missing as we don't really know what it is that you are doing. But if you did not take RWD considerations in mind, I'm assuming there are quite a few things that you are missing.

You should look into responsive web-design (RWD), you can find quite a bit of information about it around the web, starting with wikipedia responsive web design.

You can consult some books if you prefer: Responsive Web Design (Brief Books for People Who Make Websites, No. 4)

It's all about using relative positioning / margins instead of fixed or absolute positioning.


答:
Unfortunately, there is no 'magic bullet' solution to your problem.  What you are talking about is called Responsive Web Design and it takes a lot of experience to be able to efficiently design websites to look great on all screen sizes.

I recommend that you start by doing some reading on responsive web design,  there are plenty of good places to get started on this topic.

Additionally, mastering HTML / CSS will help-- There is a free course that is pretty good from codecademy.com.  That should get you up to speed pretty quickly.

To more directly answer your question: people most commonly use some combination of javascript and CSS media queries to resize content / DOM elements

Title: How to make a website be formatted correctly on all screen sizes?

Body: I recently made a pure (didn't use Bootstrap or anything else) HTML 'website' (didn't actually give it a url) on my laptop, but when I opened the website on my desktop, it looked horrible and nothing was formatted correctly (elements were too small, margins were too big or too small, etc.). What should I do to make sure my website fits on all screen sizes?</p>