问:
Client-Server Application Object with child Objects
Actually I'm going to build an Client Server Application, at the Login I recive the User Object from the Server.
An user has a List of tasks, but I don't want to load them at the Login.
So what would be an good style to recive the Tasks of an user.
Should my user have an "GetTasks()" function which will access the server and will return the Tasks, which would be an strongly object orientated method.
Or should I Use an Service, which has a function that takes the user as parameter and returns the task.</p>

答:
It is not quite clear, what you want.

at the Login I recive the User Object from the Server

An user has a List of tasks, but I don't want to load them at the Login

So what would be an good style to recive the Tasks of an user

If I understand that correctly, the list of tasks could be long, so receving the list of task would be something which has a negative impact on the time it takes to log in; so you want to decouple that?

Then the first question is, why you are retrieving a whole user object at all? A slimmed down model would do.

Should my user have an "GetTasks()" function which will access the server and will return the Tasks, which would be an strongly object orientated method. Or should I Use an Service, which has a function that takes the user as parameter and returns the task.

Without code and your poor description it is hard to guess, what you are doing at all.

You should distinguish between

Frontend

If you have a "model" (e.g. a Backbone-Model), which represents a user, then a "method" getTasks() makes perfect sense

Backend

On the serverside, a Service is needed to retrieve the tasks. I suggest building a REST ful service where you would have an URI like api/users/{id}/tasks which would return a list of tasks for a user with a given id (which is given as a "path"-variable {id}):

```<code>{
  "tasks": [{
    "name": "task1",
    "description": "Doingstuff",
    "links": [{
      "rel": "self",
      "href": "http: //localhost: 8080/api/users/1/tasks/1"
    }]
  }],
  "links": [{
    "rel": "self",
    "href": "http: //localhost: 8080/api/users/1/tasks"
  }, {
    "rel": "user",
    "href": "http: //localhost: 8080/api/users/1"
  }]
}
</code>```

Body:
It is not quite clear, what you want.

at the Login I recive the User Object from the Server

An user has a List of tasks, but I don't want to load them at the Login

So what would be an good style to recive the Tasks of an user

If I understand that correctly, the list of tasks could be long, so receving the list of task would be something which has a negative impact on the time it takes to log in; so you want to decouple that?

Then the first question is, why you are retrieving a whole user object at all? A slimmed down model would do.

Should my user have an "GetTasks()" function which will access the server and will return the Tasks, which would be an strongly object orientated method. Or should I Use an Service, which has a function that takes the user as parameter and returns the task.

Without code and your poor description it is hard to guess, what you are doing at all.

You should distinguish between

Frontend

If you have a "model" (e.g. a Backbone-Model), which represents a user, then a "method" getTasks() makes perfect sense

Backend

On the serverside, a Service is needed to retrieve the tasks. I suggest building a REST ful service where you would have an URI like api/users/{id}/tasks which would return a list of tasks for a user with a given id (which is given as a "path"-variable {id}):

{
  "tasks": [{
    "name": "task1",
    "description": "Doingstuff",
    "links": [{
      "rel": "self",
      "href": "http: //localhost: 8080/api/users/1/tasks/1"
    }]
  }],
  "links": [{
    "rel": "self",
    "href": "http: //localhost: 8080/api/users/1/tasks"
  }, {
    "rel": "user",
    "href": "http: //localhost: 8080/api/users/1"
  }]
}


问:
Are data type declarators like "int" and "char" stored in RAM when a C program executes?
When a C program is running, the data is stored on the heap or the stack. The values are stored in RAM addresses. But what about the type indicators (e.g., int or char)? Are they also stored?

Consider the following code:

```<code>char a = 'A';
int x = 4;
</code>```

I read that A and 4 are stored in RAM addresses here. But what about a and x? Most confusingly, how does the execution know that a is a char and x is an int? I mean, is the int and char mentioned somewhere in RAM?

Let's say a value is stored somewhere in RAM as 10011001; if I am the program which executes the code, how will I know whether this 10011001 is a char or an int?

What I don't understand is how the computer knows, when it reads a variable's value from an address such as 10001, whether it is an int or char. Imagine I click on a program called anyprog.exe. Immediately the code starts executing. Does this executable file include information on whether the variables stored are of the type int or char?

答:
You have to distinguish between compiletime and runtime on the one hand and code and data on the other hand.

From a machine perspective it is no difference between what you call code or instructions and what you call data. It all comes down to numbers. But some sequences - what we would call code - do something what we find usefull, others would simply crash the machine.

The work which is done by the CPU is a simple 4 step loop:

Fetch "data" from a given address

Decode the instruction (i.e. "interpret" the number as an instruction)

Read an effective address

Execute and store results

This is called the instruction cycle.

I read that A and 4 are stored in RAM addresses here. But what about a and x?

a and x are variables, which are placeholders for the addresses, where the program could find the "content" of the variables. So, anytime the variable a is used, there is effectively the address of the content of a used.

Most confusingly, how does the execution know that a is a char and x is an int?

The execution doesn't know anyting. From what was said in the introduction, the CPU only fetches data and interprets this data as instructions.

The printf-function is designed to "know", what kind of input you are putting into it, i.e. its resulting code gives the right instructions how to deal with a special memory segment. Of course, it is possible to gnerate nonsense output: using an address, where no string is stored along with "%s" in printf() will result in nonsense output stopped only by a random memory location, where a 0 (\0) is.

The same goes for the entry-point of a programm. Under the C64 it was possible to put your programs in (nearly) every known address. Assembly-Programs were started with an instruction called sys followed by an address: sys 49152 was a common place to put your assembler code. But nothing prevented you from loading e.g. graphical data into 49152, resulting in a machine crash after "starting" from this point. In this case, the instruction cycle started with reading "graphical data" and trying to interpret it as "code" (which of course made no sense); the effects were sometmes astounding ;)

Let's say a value is stored somewhere in RAM as 10011001; if I am the program which executes the code, how will I know whether this 10011001 is a char or an int?

As said: The "context" - i.e. the previous and next instructions - help treating the data in the way we want it. From a machine perspective, there is no difference in any memory location. int and char is only vocabulary, which makes sense in compiletime; during runtime (on a assembly level), there is no char or int.

What I don't understand is how the computer knows, when it reads a variable's value from an address such as 10001, whether it is an int or char.

The computer knows nothing. The programmer does. The compiled code generates the context, which is necessary to generate meaningful results for humans.

Does this executable file include information on whether the variables stored are of the type int or char

Yes and No. The information, whether it is an int or a char is lost. But on the other hand, the context (the instructions which tell, how to deal with memory locations, where data is stored) is preserved; so implicitely yes, the "information" is implicitely available.

ContentLicense: CC BY-SA 3.0


问:
Expert advice needed for a NoSql Database
At our company, I have been given the task to develop a Mobile Application (iOS, Android and in the future, maybe Windows).
Given those devices, it's likely that we'll have a high number of installations spread over all those devices.

Off course, for a mobile application it's very important to be responsive, so therefore we've decided to move from a classic SQL Environment (SQL Server) to a No-Sql (MongoDB) solution.

We've chosen this approach because the platform is highly scaleable which can come in handy in the future.

You need to know that I'm totally new to the No-Sql story, so don't blame me on eventual dumb questions, I'm here to learn the best practices.

Let's start by looking at the data that I do need to import.

The application which our company is developing is an application to browse through a catalogue of articles which can potentially be purchased.
There's a specific hierarchy of those articles which I'll try to explain in the image below:

To explain the image above a bit in words:

1 have a classification on the root level (for example - kitchen articles), under which I can have (not mandatory) another classification (for example knives).
This goes for 4 levels deep.

Under each classification I can have an Article Group, (for example: knife, steel, black), and then under each article group, I always have some articles (for example: Blade: 20cm, Blade: 22cm, Blade 24cm).

To give you an idea about the knife, see the following Json (I'll try to explain it the best possible way):

```<code>{
   "Name":"Kitchen",
   "Classifications":[
      {
         "Name":"Knives",
         "Article Groups":[
            {
               "Name":"Knive Steel Black",
               "Articles":[
                  {
                     "ArticleGTIN":"684351654984"
                  }
               ]
            }
         ]
      }
   ]
}
</code>```

This is roughly how the data is stuctured.
One more thing which is very important is that articles can have multiple properties.

Below is a snippet of just an article with some properties on it:

```<code>{
   "ArticleGTIN":"984651164",
   "Properties":[
      {
         "Name":"Length",
         "Value":"20cm",
      },
      {
         "Name":"Hardness",
         "Value":"1",
      }
   ]
}
</code>```

Now, for the application, I need to be able through the catalogue, thus:

Seeing all the classifications on the root level.

If a classification is selected, see all child classifications.

For each an every classification, I need to be able to view the article groups.

For each an every article group, I need to be able to view the articles.

Most important: I need to be able to filter at all the given properties for an example. By this I mean that I must be able to say: find me all knives with a hardness >= 2 and where the Length is at least 10cm (I think you get the point). It's kind of a filter like the search on Amazon:

The problem which I'm facing is that I don't know exactely how I should store my data to keep my application as performant as possible.
I do have a couple of options in mind:

One big collection named "Classifications" in which everything is stored. So, one 'parent' node and all child nodes under it (see diagram above).

Many small collection with each entry in a collection referring to another colletion, for example, a collection with classifications and then another collection with article groups. Each article group does hold a reference (based on an 'Id' field with the correct classification).

Create collections that matches the data exposed on the application. For example the search, I can create a collection with only articles and their given properties.

...

I hope that someone can give an answer on what's best suited here.

One more thing on which I'm looking for answer.
To use the application, you need to be authenticated. For that I was using Microsoft Authentication Framework (Entity Framework, SQL Server).
Is it best to keep this, and thus mixing SQL Server and MongoDB or is it better to store everything in a single database technology?

Note: I'm looking for facts and best practices. Please include a why or why-not in your answer so that I can make the best decesion based on the given answers.

答:
```<code>article: {
    articleGTIN: value,
    properties: [
        { name: value, value: value },
        { name: value, value: value }
    ],
    articleGroups: value,
    classification: value
}
</code>```

NoSQL databases is also called document database, that means the entity of the database should be a document like structure.

Think of your articles as document, a paper you hav in front of you and everything else is META data.

Use the global trade item as the unique key and if you need more multiple classifications or articleGroupd per article, embedd them, ie. treat them as I suggest to use the properties, as an array of objects.

Body:
article: {
    articleGTIN: value,
    properties: [
        { name: value, value: value },
        { name: value, value: value }
    ],
    articleGroups: value,
    classification: value
}

NoSQL databases is also called document database, that means the entity of the database should be a document like structure.

Think of your articles as document, a paper you hav in front of you and everything else is META data.

Use the global trade item as the unique key and if you need more multiple classifications or articleGroupd per article, embedd them, ie. treat them as I suggest to use the properties, as an array of objects.


问:
How to design a class for a fixed-length id?
I'm building an app in C# that needs a fixed-length id, which is a string representation of a hex number. E.g. "0fa5" is an example of such an id of length 4. The length would not need to change within the program at runtime, but may be changed in the future or for example in tests.

My question is about how to approach designing such a class. I've come up with two methods so far:

The first would be making a single class, IdType that has a static method SetExpectedLength(int) that should only be called once, otherwise it gives an exception:

```<code>class IdType
{
    public static int ExpectedLength {get; private set;} = 0;
    public string Id {get; private set;} = "";

    public IdType(string id)
    {
        if (IdType.ExpectedLength== 0)
            throw new Exception("SetExpectedLength needs to be called first");

        if (id.Length != IdType.ExpectedLength)
            throw new Exception("Length constraints not satisfied!");

        this.Id = id;
    }

    public static void SetExpectedLength(int length)
    {
        if (IdType.Length == 0)
            IdType.ExpectedLength = length;
        else throw new Exception("SetExpectedLength can only be called once");
    }

    // other operations here...
}
</code>```

The other approach would be making a base abstract class and deriving IdTypes of different lengths from it:

```<code>abstract class IdType
{
    public string Id {get; protected set;}
}

// IdType of length 4
class IdType4 : IdType
{
    public readonly int Length = 4;

    public IdType4(string id)
    {
        if (id.Length != this.Length)
            throw new Exception("Length constraints not satisfied!");

        this.Id = id;
    }
}
</code>```

The second approach seems more clean, however if I need a new length for the ids I would have to make a new class AND replace the instance of the old class everywhere it is used.

What is the best practice in this case? Is there another design pattern that I can use?

答:
Your code is much too complicated for such a simple requirement. This is because you are focusing on the representation (four hex characters) when you should be focusing on the thing represented, which is merely a two-byte integer. A C# ushort is precisely that type.

For convenience, you could create a struct (not a class) that contains a short and methods to convert to/from a four-byte hex string.

If you need arbitrary precision, then use System.Numerics.BigInteger instead. BigInteger already has methods to convert to and from strings.


问:
When NOT to use a framework
Today, one can find a framework for just about any language, to suit just about any project.  Most modern frameworks are fairly robust (generally speaking), with hour upon hour of testing, peer reviewed code, and great extensibility.

However, I think there is a downside to ANY framework in that programmers, as a community, may become so reliant upon their chosen frameworks that they no longer understand the underlying workings, or in the case of newer programmers, never learn the underlying workings to begin with.  It is easy to become specialized to a degree that you are no longer a 'PHP programmer' (for example), but a "Drupal programmer", to the exclusion of anything else.

Who cares, right?  We have the framework!  We don't need to know how to "do it by hand"!  Right?

The result of this loss of basic skills (sometimes to the extent that programmers who don't use frameworks are viewed as "outdated") is that it becomes common practice to use a framework where it is not required or appropriate.  The features the framework facilitates wind up confused with what the base language is capable of.  Developers start using frameworks to accomplish even the most basic of tasks, so that what once was considered a rudimentary process now involves large libraries with their own quirks, bugs, and dependencies.  What was once accomplished in 20 lines is now accomplished by including a 20,000 line framework AND writing 20 lines to use the framework.

Conversely, one does not want to reinvent the wheel.  If I'm writing code to accomplish some basic, common little task, I might feel like I am wasting my time when I know that framework XYZ offers all the features I am after, and a whole lot more.  The "whole lot more" part still has me worried, but it doesn't seem that many even consider it anymore.

There has to be a good metric to determine when it is appropriate to use a framework.  What do you consider the threshold to be, how do you decide when to use a framework, or, when not.

答:
I tend to work most with web applications and even though I'm trying to be general, my answer might not apply to your area of programming.

I am also going to use "framework" synonymical with "library".

Before implementing a framework, one must consider a few things, here are a few general examples.

#1. Will the framework save time and effort?

The answer to this question is almost always yes. Frameworks tend to be built to solve specific problems, and solve them very well. For instance, frameworks such as EntityFramework can save you entirely from writing SQL-code. Which can be fantastic if your programming team is not fluent in SQL.

Frameworks are built to either, a) add a programmer-friendly interface to otherwise complex components or b) add abstraction to already well known (or established) components.

The latter (or even the former in some cases) can actually get in the way of development. This applies especially when you or your programming team is going to implement a new framework, in which they have never worked before.

This could potentially slow down your development process, which could potentially be costly.

#2 The scale of your application

It is said that "anything worth doing is worth overdoing", but usually that's not the case. There's probably no good reason to implement a super-sized framework if the point of your application is to print "potato".

When you are developing a application (be it web, desktop, mobile or any other  conceivable type of application) — if you feel that the size of your framework "dwarves" your (maybe future) implementation of it, then this might be a big warning sign that your framework might just bloating your application. A good anecdote would be if you included jQuery, just to add a "loaded"-class to your body-tag when the document is ready. Doing that with just native JavaScript might be a tiny bit harder, but it doesn't bloat your application.

On the other hand if a framework does a lot of dirty work on the inside (i.e. database frameworks), then it might be viable to implement it, even if you only are "partially" using the framework. A good anecdote would be to not try to build your own ADO.NET or MongoDB-driver, just because you don't need to utilize the entire library.

Sometimes frameworks come open-source (and with 'do-whatever-you-want'-licenses). This opens up a new possibility where a programming team might only opt for parts of a framework.

This ultimately ties back to question #1 and #3.

#3 Impact.

Sometimes implementing a framework can directly impact the end user.
This is especially true for web applications, since having big client-side frameworks might negatively affect the end-user's experience. Users with slower machines might experience slow rendering, performance issues with javascript or similar issues caused by sub-par machines. User with slow connections might experience slow (at least initial) loading times.

Even in other types applications, end-users might be negatively impacted by your application-dependencies. Frameworks at least always take up some disk space, and if you are developing a mobile app (or even a desktop app) this might be needed to be taken into consideration.

Server-side frameworks (even more web-specific) will most likely not affect your end-users, but it will affect your infrastructure. Some frameworks have dependencies themselves which might require you to restart your web server, either just the service or the server entirely.

Some frameworks might also be very resource-heavy.

This of course ties back to point #1 and #2.

It's all just a big "circle of considerations", and there is no real scientific method for deciding whether you should implement a framework or not.

Corbin March summarized it very well:

The groups I've worked with all do the same thing - make a guess at
  costs and benefits, choose the most productive route, and hope they're
  right. It's not terribly scientific - one part intuition, three parts
  experience, one part susceptibility to marketing, one part cunning,
  and five parts rank opinion.

It's also important not to be elitist. Frameworks are tools which are meant to be used. I know people of both extremes; on the one side you have the guy making life very hard for himself, on the other side you have the guy who builds slow, bloated applications.

All frameworks have use-cases, it's just a matter of implementing them for the right purposes.

ContentLicense: CC BY-SA 2.5

Title: When NOT to use a framework


答:
Short answer, the type is encoded in the CPU instructions the compiler generates.

Although the information about the type or size of the information is not directly stored, the compiler does keep track of this information when accessing, modifying and storing values in these variables.

how does the execution know that a is a char and x is an int?

It doesn't, but when the compiler produces the machine code it knows. An int and a char can be of different sizes. In an architecture where where a char is the size of a byte and an int is 4 bytes, then variable x is not in address 10001, but also in 10002, 10003 and 10004. When code needs to load the value of x into a CPU register, it uses the instruction for loading 4 bytes. When loading a char, it uses the instruction to load 1 byte.

How to choose which of the two instructions? The compiler decides during the compilation, it's not done at runtime after inspecting the values in memory.

Note as well that registers can be of different sizes. On Intel x86 CPUs the EAX is 32 bits wide, half of it is AX, which is 16, and AX is split into AH and AL, both 8 bits.

So if you want to load an integer (on x86 CPUs), you use the MOV instruction for integers, to load a char you use the MOV instruction for chars. They are both called MOV, but they have different op codes. Effectively being two different instructions. The type of the variable is encoded in the instruction to use.

The same thing happens with other operations. There are many instructions for performing addition, depending on the size of operands, and even if they are signed or unsigned. See https://en.wikipedia.org/wiki/ADD_(x86_instruction) which list different possible additions.

Let's say a value is stored somewhere in RAM as 10011001; if I am the program which executes the code, how will I know whether this 10011001 is a char or an int

First, a char would be 10011001, but an int would be 00000000 00000000 00000000 10011001, because they are different sizes (on a computer with the same sizes as mentioned above). But lets consider the case for signed char vs unsigned char.

What is stored in a memory location can be interpreted anyway you want. Part of the responsibilities of the C compiler is to ensure that what is stored and read from a variable is done in a consistent manner. So it's not that the program knows what's stored in a memory location, but that it agrees before hand that it will always read and write the same kind of things there. (not counting things like casting types).

Title: Are data type declarators like "int" and "char" stored in RAM when a C program executes?

Body:
When a C program is running, the data is stored on the heap or the stack. The values are stored in RAM addresses. But what about the type indicators (e.g., int or char)? Are they also stored?

Consider the following code:

```<code>char a = 'A';
int x = 4;
</code>```

I read that A and 4 are stored in RAM addresses here. But what about a and x? Most confusingly, how does the execution know that a is a char and x is an int? I mean, is the int and char mentioned somewhere in RAM?

Let's say a value is stored somewhere in RAM as 10011001; if I am the program which executes the code, how will I know whether this 10011001 is a char or an int?

What I don't understand is how the computer knows, when it reads a variable's value from an address such as 10001, whether it is an int or char. Imagine I click on a program called anyprog.exe. Immediately the code starts executing. Does this executable file include information on whether the variables stored are of the type int or char?


问:
Implementing the State Pattern with Object.setPrototypeOf()
Take a look at this implementation of the state pattern in JavaScript:

```<code>var ON = {
    switch: function() {
        Object.setPrototypeOf(this, OFF);
        this.state = "OFF";
    }
}

var OFF = {
    switch: function() {
        Object.setPrototypeOf(this, ON);
        this.state = "ON";
    }
}

var lightBulb = Object.create(OFF);
lightBulb.switch(); // lightBulb.state is "ON"
lightBulb.switch(); // lightBulb.state is "OFF"
</code>```

Two advantages that I like here are that the context (lightBulb) doesn't have to keep a reference to the active state, and that it doesn't have to define a switch() method just to delegate that call to its active state's switch() method.  In other words, less boilerplate code.

I'm new to JavaScript, and haven't done any serious development with it.  I would like to know if there are any pitfalls I am missing?  Particularly, I'm wondering about the fact that I'm changing the prototype of a constructed object.  Is this a no-no in JavaScript land?

答:
This would work, but it's a very unusual way of accomplishing this task, so I would avoid it unless it's meant to be part of a learning exercise in how prototypes work.

Just to make sure we're on the same page, the "typical way" I have in mind is this:

```<code>var Switch = function() {
    this.state = "ON";
};

Switch.prototype.switch = function() {
    if(this.state === "ON") {
        this.state = "OFF";
    } else {
        this.state = "ON";
    }
};
</code>```

I would prefer this "traditional" version over your "circular prototypes" version because:

If I came across the circular prototype version "in the wild", I'd have to spend some time either working out what it was supposed to do, or convincing myself that this really does what it's supposed to do (as I did for a few minutes when I found this question), precisely because it's so unusual. The traditional one I could probably glance at once and immediately move on.

Changing prototype chains at runtime is generally frowned upon because it can result in extremely unintuitive behavior. In particular, mistakes in such code can be extremely hard to debug. It's a lot like self-modifying code in lower-level languages. Your example happens to be very simple, but if this was part of a real program, it would no doubt end up with a much more complex interface on each state and/or far more than two states to switch between. Imagine trying to debug code when the object you're watching in the debugger changes its type on every method call, and each of those types has different expectations about its internal state.

The circular prototypes version already has a little bit of code duplicated between the two objects. If this was a more complicated object, there would no doubt be much more duplication, which would make it a lot harder to add new features to this object without making a silly mistake somewhere (which we'd then have to debug!). And whenever two of the objects differed in some way, it'd be impossible to tell if that difference was intentional or not.

Although optimization and engine internals aren't my specialty, I'm fairly sure Javascript engines are designed to heavily optimize prototype lookups (since every single member access and method call involves a lookup), and it's much easier to do that when the prototype chains remain static. Besides, most code doesn't change the chains at runtime, so most optimizers probably assume that's the norm.

I also don't really understand your alleged advantages.

the context (lightBulb) doesn't have to keep a reference to the active state

Technically you're right, but in practice it just "keeps that reference" in the form of a prototype link to a closure which knows the state (but won't tell anyone what it is), which is a lot less direct and less flexible than simply holding the state as a member variable. I also don't see why you'd want a light switch to not know whether it's turned on or not; that seems like trying to decouple things which cannot and should not be decoupled.

it doesn't have to define a switch() method just to delegate that call to its active state's switch() method

You appear to be comparing your version to an implementation where lightSwitch.switch() would call ON.switch() or OFF.switch(). I would also criticize that implementation for its unnecessary delegation, but since it's very easy to write a traditional version that simply doesn't do that, it's not clear how this is an advantage.

In other words, less boilerplate code.

Our versions seem about equal in length/boilerplate.

Finally, here's a hypothetical scenario that might help to demonstrate some of the abstract points I was making above: Say you want to give your lightSwitch an isOn() method that returns whether or not it's on. How would you do that?

With the traditional version, the solution is a trivial one-liner with no obvious disadvantages. With the circular prototypes version, I can't think of any clean way of adding it (i.e., no code duplication, no direct prototype comparisons) without essentially reimplementing the whole class in a more traditional way.

Body:
This would work, but it's a very unusual way of accomplishing this task, so I would avoid it unless it's meant to be part of a learning exercise in how prototypes work.

Just to make sure we're on the same page, the "typical way" I have in mind is this:

var Switch = function() {
    this.state = "ON";
};

Switch.prototype.switch = function() {
    if(this.state === "ON") {
        this.state = "OFF";
    } else {
        this.state = "ON";
    }
};

I would prefer this "traditional" version over your "circular prototypes" version because:

If I came across the circular prototype version "in the wild", I'd have to spend some time either working out what it was supposed to do, or convincing myself that this really does what it's supposed to do (as I did for a few minutes when I found this question), precisely because it's so unusual. The traditional one I could probably glance at once and immediately move on.

Changing prototype chains at runtime is generally frowned upon because it can result in extremely unintuitive behavior. In particular, mistakes in such code can be extremely hard to debug. It's a lot like self-modifying code in lower-level languages. Your example happens to be very simple, but if this was part of a real program, it would no doubt end up with a much more complex interface on each state and/or far more than two states to switch between. Imagine trying to debug code when the object you're watching in the debugger changes its type on every method call, and each of those types has different expectations about its internal state.

The circular prototypes version already has a little bit of code duplicated between the two objects. If this was a more complicated object, there would no doubt be much more duplication, which would make it a lot harder to add new features to this object without making a silly mistake somewhere (which we'd then have to debug!). And whenever two of the objects differed in some way, it'd be impossible to tell if that difference was intentional or not.

Although optimization and engine internals aren't my specialty, I'm fairly sure Javascript engines are designed to heavily optimize prototype lookups (since every single member access and method call involves a lookup), and it's much easier to do that when the prototype chains remain static. Besides, most code doesn't change the chains at runtime, so most optimizers probably assume that's the norm.

I also don't really understand your alleged advantages.

the context (lightBulb) doesn't have to keep a reference to the active state

Technically you're right, but in practice it just "keeps that reference" in the form of a prototype link to a closure which knows the state (but won't tell anyone what it is), which is a lot less direct and less flexible than simply holding the state as a member variable. I also don't see why you'd want a light switch to not know whether it's turned on or not; that seems like trying to decouple things which cannot and should not be decoupled.

it doesn't have to define a switch() method just to delegate that call to its active state's switch() method

You appear to be comparing your version to an implementation where lightSwitch.switch() would call ON.switch() or OFF.switch(). I would also criticize that implementation for its unnecessary delegation, but since it's very easy to write a traditional version that simply doesn't do that, it's not clear how this is an advantage.

In other words, less boilerplate code.

Our versions seem about equal in length/boilerplate.

Finally, here's a hypothetical scenario that might help to demonstrate some of the abstract points I was making above: Say you want to give your lightSwitch an isOn() method that returns whether or not it's on. How would you do that?

With the traditional version, the solution is a trivial one-liner with no obvious disadvantages. With the circular prototypes version, I can't think of any clean way of adding it (i.e., no code duplication, no direct prototype comparisons) without essentially reimplementing the whole class in a more traditional way.


问:
White Boards -- Who Uses Them?
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!

答: I use a large full length mirror instead of a white board, mainly because it was already present in the room.   I use it mainly for diagrams to think about, as well as TODO lists.  It also helps me stay on my diet. </p>

Title: White Boards -- Who Uses Them?


答:
I'm building an app in C# that needs a fixed-length id, which is a string representation of a hex number.

So use a string. Anything else is a waste of time.

On the day you find that you somehow passed an ID code string of the wrong length, add an extension method to check the string length.

Title: How to design a class for a fixed-length id?

Body:
I'm building an app in C# that needs a fixed-length id, which is a string representation of a hex number. E.g. "0fa5" is an example of such an id of length 4. The length would not need to change within the program at runtime, but may be changed in the future or for example in tests.

My question is about how to approach designing such a class. I've come up with two methods so far:

The first would be making a single class, IdType that has a static method SetExpectedLength(int) that should only be called once, otherwise it gives an exception:

```<code>class IdType
{
    public static int ExpectedLength {get; private set;} = 0;
    public string Id {get; private set;} = "";

    public IdType(string id)
    {
        if (IdType.ExpectedLength== 0)
            throw new Exception("SetExpectedLength needs to be called first");

        if (id.Length != IdType.ExpectedLength)
            throw new Exception("Length constraints not satisfied!");

        this.Id = id;
    }

    public static void SetExpectedLength(int length)
    {
        if (IdType.Length == 0)
            IdType.ExpectedLength = length;
        else throw new Exception("SetExpectedLength can only be called once");
    }

    // other operations here...
}
</code>```

The other approach would be making a base abstract class and deriving IdTypes of different lengths from it:

```<code>abstract class IdType
{
    public string Id {get; protected set;}
}

// IdType of length 4
class IdType4 : IdType
{
    public readonly int Length = 4;

    public IdType4(string id)
    {
        if (id.Length != this.Length)
            throw new Exception("Length constraints not satisfied!");

        this.Id = id;
    }
}
</code>```

The second approach seems more clean, however if I need a new length for the ids I would have to make a new class AND replace the instance of the old class everywhere it is used.

What is the best practice in this case? Is there another design pattern that I can use?


问:
Code review lags behind the Deliver/Test Cycle
In our Agile process we have 2-week Sprints. Tasks are delivered on a daily basis (daily builds), and the Test Team completes their testing immediately the next day or even the same day.

We also have Dev code reviews, which require some time (1-2 hrs), so they are scheduled 3 times a week: Mon-Weds-Fri. Developers get together and suggest how to improve/refactor code.

Our problem is, by the time Action Items come up after a code review, most of the tasks have already been tested. Testers don't want to re-test what already passed their tests. They don't care about internal dev changes.

Are we misunderstanding the Agile process? Are code reviews incompatible with a daily Release/Test cycle? We can't hold code reviews every day, as they take up everyone's time.

答:
From the sounds of it testers don't want to retest because testing is a painful/expensive process.

Test automation both by devs and testers is a huge bonus for teams trying to work in an agile way. The cheaper, easier, and more reproduceable your tests are then the more you can execute them - and the less resistance you'll get to changing something.

Done a quick refactor based on some dev feedback? Press the big red button that executes your regression/smoke suite and do a quick manual once-over to check for any visual problems that might have cropped up. Easy!

Once you're in a place like that, re-testing won't be a chore - it'll be second nature.

OwnerDisplayName: gene b.


问:
Can I use GPL software in a commercial application
I have 3 questions about the GPL here:

If I use GPL software in my application, but don't modify or distribute it, do I have to release my application under the GPL?

What if I modify some software that my application uses. Then do I have to release my application under the GPL, or can I just supply the modified software under the GPLs terms.

And what if I use GPL software, but don't modify it, can I distribute it with my application?

My case in point is, I have a PHP framework which I use the GeSHi library to highlight some output.

Because GeSHi is GPL, does my framework have to be GPL?

Can I modify GeSHi for particular use cases of my application if I supply the modifications back to the GeSHi maintainers?

Can I redistribute my framework with GeSHi?

答:
We can force such rules in the jungle, but in real life (juridical of country or state) it depends on who, whom, when and what.

The legal problem (law) raise when you do an act of distributing GPL program as binary or library on non GPL OS. GPL program is infecting and infected the parent and the child non GPL process (proprietary and even other open source license) from the perspective of law. Infecting means derived program violate GPL, infected means GPL program violate its own license. No problem exists when you compile a distributed GPL source as act individual (person, org, company).


问:
'Encapsulation Vs Performance' trade-off in a lockable linked list
Main purpose of encapsulation is to protect in-variants of any class(in java).

Here is the complete code for class DList/class lockDList/class DListNode/class LockDListNode.

class DList and it's subclass class LockDList has following invariants.

```<code>/* DList invariants:
   *  1)  sentinel != null.
   *  2)  For any DListNode x in a DList, x.next != null.
   *  3)  For any DListNode x in a DList, x.prev != null.
   *  4)  For any DListNode x in a DList, if x.next == y, then y.prev == x.
   *  5)  For any DListNode x in a DList, if x.prev == y, then y.next == x.
   *  6)  size is the number of DListNodes, NOT COUNTING the sentinel,
   *      that can be accessed from the sentinel (sentinel) by a sequence of
   *      "next" references.
   */
</code>```

But the user of class LockDList and class DList can pass/receive the wrong list node. This leads to breaking of encapsulation because of the only reason i.e., in-variants are not protected, because user can pass wrong node to class DList or class LockDList For example, below is the public method next in class DList.

```<code>public DListNode next(DListNode node) {
      if ((node == null) || (node.getNext() == this.sentinel)){
          return null;
      }else{
          return node.getNext();
      }
  }
</code>```

Most of the production code try introduce such O(1) implementation, keeping item of class DListNode as public.

Is there a design decision that can be suggested to maintain encapsulation without performance hit?

答:
Your major problem comes from the user passing a node that do not belong to the list, as you said in your comment:

[...] if the user passes node of list1 to list2 by saying
  list2.someMethod(nodeOfList1)

You could try to avoid letting the user manipulate nodes, in which case you would need an indirect way to access them, but this pushes the problem one step further. What you need to do in this case is the check that the node belongs to the list. When this is true, then your invariants are satisfied.

You can add an owner reference from DListNode to DList and initialize it during construction: for example, dlist.insertBack(Object) would return a DListNode which references dlist. The owner is not mutable and can be made final public (or, use a getter).
Then, you must check that this == node.owner when manipulating nodes inside list operations, or throw a runtime error.


答:
You can add an attribute myDList to the class DListNode and implement a method like next in the following manner:

```<code>public DListNode next(DListNode node) {
   if (node == null)
      return null;
   if(node.getMyDList()!=this)
      throw // ...some exception here
   if (node.getNext() == this.sentinel)
      return null;
   return node.getNext();
}
</code>```

That will not add a significant performance penalty, but it adds a memory penalty, because every node has to hold an extra reference now.

EDIT: you can even avoid the memory penalty when you follow the suggestion of Olaf Dietsche. Introducing an iterator class will avoid the necessity for a DList.next() function at all, and the corresponding next function of the iterator will need no parameters, which eliminates the possibility of passing any inconsistent values.

Title: 'Encapsulation Vs Performance' trade-off in a lockable linked list

Body:
Main purpose of encapsulation is to protect in-variants of any class(in java).

Here is the complete code for class DList/class lockDList/class DListNode/class LockDListNode.

class DList and it's subclass class LockDList has following invariants.

```<code>/* DList invariants:
   *  1)  sentinel != null.
   *  2)  For any DListNode x in a DList, x.next != null.
   *  3)  For any DListNode x in a DList, x.prev != null.
   *  4)  For any DListNode x in a DList, if x.next == y, then y.prev == x.
   *  5)  For any DListNode x in a DList, if x.prev == y, then y.next == x.
   *  6)  size is the number of DListNodes, NOT COUNTING the sentinel,
   *      that can be accessed from the sentinel (sentinel) by a sequence of
   *      "next" references.
   */
</code>```

But the user of class LockDList and class DList can pass/receive the wrong list node. This leads to breaking of encapsulation because of the only reason i.e., in-variants are not protected, because user can pass wrong node to class DList or class LockDList For example, below is the public method next in class DList.

```<code>public DListNode next(DListNode node) {
      if ((node == null) || (node.getNext() == this.sentinel)){
          return null;
      }else{
          return node.getNext();
      }
  }
</code>```

Most of the production code try introduce such O(1) implementation, keeping item of class DListNode as public.

Is there a design decision that can be suggested to maintain encapsulation without performance hit?

Body:
You can add an attribute myDList to the class DListNode and implement a method like next in the following manner:

public DListNode next(DListNode node) {
   if (node == null)
      return null;
   if(node.getMyDList()!=this)
      throw // ...some exception here
   if (node.getNext() == this.sentinel)
      return null;
   return node.getNext();
}

That will not add a significant performance penalty, but it adds a memory penalty, because every node has to hold an extra reference now.

EDIT: you can even avoid the memory penalty when you follow the suggestion of Olaf Dietsche. Introducing an iterator class will avoid the necessity for a DList.next() function at all, and the corresponding next function of the iterator will need no parameters, which eliminates the possibility of passing any inconsistent values.


答:
You don't expose what the user doesn't need to know.

If the main interface is just DList, then you should not expose DListNode to the user of your class(es). You may make DListNode a private class, which is manipulated internally by DList only.

In the case of iterating through your list, e.g. next(), you may move this to an enumerator or iterator like class, which contains an associated list. This way you hide the DListNode class and there's no way for the user to accidentially pass nodes from one list to another.

If you have no way of hiding such classes, you must add some sort of ownership in these implementation classes and check them, to be sure no accident happens.


问:
Does function pointer have the same expressive power as function as parameter?
In functional programming language, a function can be passed as an argument to another function. In programming language like C/C++, a function pointer referring to a function can be passed to a function that can invoke the external function through dereference.

Then, does function pointer have the same expressive power as function as parameter in functional programming language?

答:
Consider (some of) what a function pointer has:

type

and what you can do with it:

pass it as an argument

call it

return it as result

assign it to a variable/store it

compare it to another pointer of the same type

Functions as parameters is only one of the operations on this list, thus is less powerful than function pointers. However, this merely indicates that the two aren't the proper features to compare when it comes to functional programming.

Functions as parameters is just one of the language properties of higher-order functions (HOFs), which can:

accept functions as arguments

call passed functions

return functions

Additionally, in a typed language HOFs imply there are function types. Functional languages have all these, thus support HOFs. All the HOF properties are on the function pointer operations list, thus function pointers allow HOFs. Even without function pointers, some procedural languages support some or all of these (often the first two), sometimes with limitations. For example, Modula-2 supports function types and all three operations (with the limitation that the function values be top-level user functions, as opposed to system functions or nested functions), thus has higher order functions. (Modula-2 also supports function pointers, but no special operations on them beyond pointer operations (e.g. you can't call a function pointer, but you can dereference it and call the result).) ISO Pascal and Algol-60 allow functions as parameters, but don't have true function types or allow functions as return values, and, in some Pascal variants, functions are at most second-order (i.e. they can't take functions that take functions), thus these languages don't truly support higher order functions (though some compilers add at additional support as language extensions).

Even HOFs isn't the proper feature for comparison. Arguably, the defining feature of functional programming is support for first-class functions, which implies the following operations on functions and language features:

higher order functions

assign functions to variables/store functions

create/combine functions

Despite having function passing, ISO Pascal and Algol-60 lack all these. In addition to HOFs, Modula-2 supports assignment (though values must be top-level functions), but not creation or combination.

Combining functions includes the composition operator, as well as other combinators. These combinators may exist at the language level, explicitly or implicitly (e.g. J's trains), or may exist idiomatically (generally as lambdas).

The only function pointer operation not among the first-class-function features is comparison. Many languages support at least reference equality, but some do not (e.g. F#). This is the potential expressiveness gap: first-class functions may not allow for comparison, and function pointers do not (in general) allow for creation & combination. Depending on the language, it may be possible to add a function comparison operator or function creation (combination easily follows from creation). Adding function creation is likely to be much harder, as it basically requires embedding a language processor. A language with function pointers but not first-order functions may have other language features (e.g. function objects in C++98 & C++03, which basically allow for function creation & combination; consider boost::function) or idioms (e.g. passing additional data along with function pointers in C, either as separate variables or bundled into structs) to make up for the lack.

Another area where first-order functions might have more expressive power than function pointers is typing. The only type-relation function pointers in C and C++ can have is type-equivalence. Function subtyping, if a language supports it, allows for expressions that can't be rewritten as type-safe expressions involving function pointers. You could still get a compilable expression using casting, but it won't be type-safe.

There are yet more features that crop up around first-class functions. These (can) include the following operations/features:

nest functions (named & anonymous/lambdas)

refer to names from outer scopes

currying

partial application

decoration

Sometimes, 1 & 2 are also included as essential sub-features of first-class functions. Not all are necessary, especially as you can implement some of them using others. Many of these have to do with creating new functions.

Nested functions, depending on the language processor implementation, may involve function creation. If the inner function definitions are evaluated each time the outer function runs, you have function creation. However, the language processor may evaluate the inner function definition only when evaluating the outer one, so that instead of creating a new inner function each time the outer one runs, it applies feature 2 and creates a new binding between the identifiers in the inner function to variables in the outer one. In functional languages, this means creating a new closure rather than a new function. Purely procedural languages probably create neither.

For example, Pascal supports nested named functions but not closures, and nested functions are compiled only once, when the rest of the source is compiled. A nested function can access the variables in the outer function, but only during the execution of the outer function (when its stack frame is active). The inner function cannot escape the outer function call.

Some of the above subfeatures can be combined in other ways to get other language features. For example:

passing + (assignment|storage) = callbacks

nested functions + returning + outer scope reference = closures

ContentLicense: CC BY-SA 4.0


答:
A function pointer (e.g. in C or C++) is only the address of some machine code (computing some function). It does know about any data except the constants embedded in the code, and the static data referenced by it.

Conceptually (e.g. in lambda-calculus) a function needs both some code to be computed, and some data to be accessed. So a function usually has bound variables, that is closed variables. Hence, a function is a mixture of code and data, that is, a closure. Practically speaking, a closure contains not only code (some "function pointer" à la C) but also data.

Notice that C++11 introduced closures, anonymous functions (a.k.a. lambda-expressions), and std::function.

Most (but not all) functional languages (e.g. Ocaml) prohibit comparing functions (that is, closures), because conceptually that would mean comparing the behavior of functions (and that is undecidable, read about Rice's theorem).

So closures are more expressive than function pointers. In this answer I claim that every function is conceptually a closure (in C, the closed values being the static data).

Because C does not have genuine closures (but n2030 is a proposal to add them to some future C2x standard), most libraries wanting "closures" are actually taking the convention that function pointers are passed as callbacks with some explicit client data (mimicking closed values); for a simple example look into GNU libc qsort_r(3). For a more complex example look into the source code and coding conventions of the GTK graphical toolkit.

From both an implementation and a theoretical point of view, closures are mixing (like objects) data and code. In the RefPerSys system this  property is used, since it aims to generate more and more of its code.

Books like the Pi-calculus (by Davide Sangiori and David walker)  ISBN 0-521-78177-9, or a Theory of objects (by Martin Abadi and Luca Cardelli) ISBN 0-387-94775-2 or Artificial Beings - the conscience of a conscious machine (by Jacques Pitrat) ISBN 9781848211018 or  Types and Programming languages (by Benjamin Pierce) ISBN 9-780282-162098 or Theories of programming languages (by John Reynolds) ISBN 0-521-59414-8 or Christian Queinnec's Lisp in Small Pieces are explaining all that much better than I could do.

If you can afford going to some university library or buying books, I recommend reading them.

Title: Does function pointer have the same expressive power as function as parameter?

Body:
In functional programming language, a function can be passed as an argument to another function. In programming language like C/C++, a function pointer referring to a function can be passed to a function that can invoke the external function through dereference.

Then, does function pointer have the same expressive power as function as parameter in functional programming language?


问:
Can I use GitHub as my mobile app's data store?
Given a relatively simple mobile app that consumes semi-static (infrequently updated by hand) data, is it a good idea to simply store said data in a public GitHub repo, in form of a structured collection of JSON files?

That data contains nothing sensitive or secret (thus there is no risk in making it public) and it doesn't need to be frequently refetched. The number of those JSON files is relatively large though, and it is advantageous to be able to tweak or add new files easily and quickly.

All of this makes storing the data on GitHub sound like a viable option. However:

Does this violate any terms of service, on either GitHub's or Apple's side of things (assuming the app is for iOS)?

Does this have serious scalability problems that make the idea not feasible beyond a simple experiment? The data won't be requested by the app very often, but the GitHub repo is still likely to receive a heavier than normal load, if the number of users grows.

Are there any other issues with this?

答:
I'm reading the Term of Service of the site and i think that you can use GitHub to host your JSON file.

But pay attention to this point:

If your bandwidth usage significantly exceeds the average bandwidth usage (as determined solely by GitHub) of other GitHub customers, we reserve the right to immediately disable your account or throttle your file hosting until you can reduce your bandwidth consumption.

And I don't know the use you will made of your data but remember that:

You may not use the Service for any illegal or unauthorized purpose. You must not, in the use of the Service, violate any laws in your jurisdiction (including but not limited to copyright or trademark laws).

Here you can find a contact page you can use to ask information via email, could be a good idea to ask before upload your files. ;-)

EDIT
I've made some research and I've found that there are a lot of site like Myjson or JSON Blob you can use to store JSON files, I hope it helps.


问:
How often do you run & test your code while programming?
Especially when writing new code from scratch in C, I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head. Don't get me wrong - I wouldn't write 1000 lines without testing at all (that would be gambling), but I would write a whole subroutine and test it (and fix it if necessary) after I think I'm finished.

On the other side, I've seen mostly newbies that run & test their code after every line they enter in the editor and think that debuggers can be a substitute for carefulness and sanity. I consider this to be a lot of distraction once you've learned the language syntax.

What do you think is the right balance between the two approaches? Of course the first one requires more experience, but does it affect productivity positively or negatively? Does the second one help you spot errors at a finer level?

答: I test for each coding concept. Sometimes this is a function or class and sometimes it is nothing more than an if statement. Once the concept works, go on to the next one.</p>


问:
Where should I put an API request in MVC?
I'm building a web application using a MVC pattern. Following this kind of architecture we can see that all the methods used to interact with database are implemented in the model.

But what happen if I have to call a service exposed by others on web? For example, I would like to access the Facebook API in order to get all the follower of my page, so, where I put these methods?

Obviously the view is not a good idea because this module is dedicated to the presentation, the controller should not be used to retrieve data but the model is usually dedicated only to the interaction with database.

So, can you give me some hint about that? And please, can you tell me if I'm making some mistakes about the MVC architecture?

答:
The model is not limited to interaction with the database, the model is responsible for getting and manipulating data.

So, to your view and controller, it should make no difference, if the data comes from a database or from a webservice or is even totally random, therefore you should do it in model.

MVC is a presentation pattern, that only separates the different representation layers.

It does not mean, that model has to be a uniform mess of spaghetti code. Your model itself can be layered as well, but the controller should not know, where the data comes from.

A public method in your model can be structured like this (Pseudo-code), which can be called by your controller:

```<code>public MyDataClass getData(int id) {
    WebServiceData wsData = WebService->getData(id);
    DatabaseData dbData = ORM->getData(id);
    return new MyDataClass(wsData, dbData);
}
</code>```

WebService and ORM may need to be instances of interfaces that can be replaced by mocks via dependency injection, but your controllers and views do not have to change for testing purposes.

Body:
The model is not limited to interaction with the database, the model is responsible for getting and manipulating data.

So, to your view and controller, it should make no difference, if the data comes from a database or from a webservice or is even totally random, therefore you should do it in model.

MVC is a presentation pattern, that only separates the different representation layers.

It does not mean, that model has to be a uniform mess of spaghetti code. Your model itself can be layered as well, but the controller should not know, where the data comes from.

A public method in your model can be structured like this (Pseudo-code), which can be called by your controller:

public MyDataClass getData(int id) {
    WebServiceData wsData = WebService->getData(id);
    DatabaseData dbData = ORM->getData(id);
    return new MyDataClass(wsData, dbData);
}

WebService and ORM may need to be instances of interfaces that can be replaced by mocks via dependency injection, but your controllers and views do not have to change for testing purposes.


问:
What locking mechanism should be used when persisting data to files
I am beginning to learn how to create web applications from a golang tutorial. For simplicity, it persists data to files instead of a database. The complete code creates a server that can handle multiple simultaneous requests, but the program doesn't seem to ensure that only one user is interacting with a fixed file at a time.

Would this create problem for "real world" applications? Does an architecture  which uses files for persistence create problems?

答:
On Linux and POSIX systems, you'll better lock the file using e.g. advisory locking like flock(2) or lockf(3) (and if your application is multithreaded, you'll better use some way -e.g. mutexes- to ensure that only at most one single thread is accessing the file). You might have one (single and well defined) goroutine reading on some go channel for that synchronization.

This advisory locking ensures that other programs & processes following the same locking convention won't simultaneously access your file (but it won't forbid some program not using locking to access or write it).

If using a database, the DBMS is often guaranteeing ACID properties.

Some libraries (like sqlite, GDBM, ....) might have some way of locking files too.

You certainly should care about not having several threads or processes writing the same file simultaneously. This would be a race condition, and such bugs are difficult to reproduce and hard to find (read about heisenbugs).


答:
Here, the model is described like this:

A model stores data that is retrieved to the controller and displayed in the view. Whenever there is a change to the data it is updated by the controller.

I'd say that the controller either includes the logic of calling the service or calls a separate Service object. If the service is separate, you can more easily create tests, say, if no connection to a service over a network is possible, some TestService could provide responses from the Service locally.

Also check out this answer that suggests that the Controller calls the service.

Title: Where should I put an API request in MVC?

Body:
I'm building a web application using a MVC pattern. Following this kind of architecture we can see that all the methods used to interact with database are implemented in the model.

But what happen if I have to call a service exposed by others on web? For example, I would like to access the Facebook API in order to get all the follower of my page, so, where I put these methods?

Obviously the view is not a good idea because this module is dedicated to the presentation, the controller should not be used to retrieve data but the model is usually dedicated only to the interaction with database.

So, can you give me some hint about that? And please, can you tell me if I'm making some mistakes about the MVC architecture?


答:
There's a common (intentional?) misunderstanding about what M, V and C are.  Not about the roles they take, but what are they.

In the original, desktop GUI definition of MVC, they were modules.  Typically an application had several of them, sometimes working in triplets, sometimes having a variety of views and models that a few controllers could mix and match.

In web frameworks, OTOH, they tend to be seen as layers, where they's only one of each and deals mostly on covering some subyacent abstraction level: "the model layer abstracts the database", "the view layer implements presentation", "the controller layer processes user input".

So, I'd say that you already have a model, dedicated to interaction with the database, and now just have to create another model, to deal with your source API.  If you make them as similar as possible, then most of the controller and view code can work seamlessly with either model.


答:
Your model should never contain any actual code, and should be seen as more of a message or a struct used to manage content manipulated by the controller and displayed by the view.

Your controller should be responsible for contacting any APIs, databases, services, etc... requesting a change and managing any necessary updates to the model.

The entire strength of the MVC pattern is that it decouples logic (the controller) from the view and state (the model). In doing so you are now guaranteed that only code in the controller can create side effects as the view and model are simply not allowed to make changes.

It also allows for better reuse of code as a model can be shared between various controllers and views.


问:
Why does a lot of Angular source code avoid enclosing the contents of a file in a closure?
I am assuming because it is a standard practice in the Angular world that, any sort of module system has to be wrapped as an Angular module and angular should be the only global variable used which will avoid any conflict. </p>

答:
It is not only standard practice in Angular, but in all software: Try to minimize global objects / variables / functions as much as possible. For reasons, see Why is Global State so Evil?

But this could be avoided in other ways as Angular, one could e.g. append your object to the ng object, but this is something like a "global state in Angular".

The main feature is the possibility of dependency injection: You inject modules into angular with a predefined interface, one implementation of the I in SOLID.

That enables you to mock objects for unit testing, and enables test driven-development.


问:
What is the difference between debugging and testing?
Introduction To Software Testing (Ammann & Offutt) mentions on p.32 a 5-level testing maturity model:

Level 0 There’s no difference between testing and debugging.

Level 1 The purpose of testing is to show that the software works.

Level 2 The purpose of testing is to show that the software doesn’t work.

Level 3 The purpose of testing is not to prove anything specific, but to reduce
the risk of using the software.

Level 4 Testing is a mental discipline that helps all IT professionals develop
higher quality software.

Although they don't go into much further detail. What are the differences between debugging and testing?

答:
Simply,

Testing means, finding the inputs that cause a Software to fail while debugging is the process of finding the fault of a given failure.


问:
Separate GUI for clients
I am writing a game in which I have a Java server/client system set up.

Everything is working great, but I reached a slight problem. I have set up a basic health system, and a GUI to go with it (for example, health bars over everyone's head), but the problem happens when I want to give every player a separate GUI (e.g. an inventory).

Obviously, it should be client-side, but I cannot for the life of me figure out how to do it. Everything that I tried resulted in the GUI's painting on top of each other and being visible for all clients.

So, how would I do it? Any input is helpful.
I have quite a bit of experience in Java programming, just not with Java servers.

The tutorial I followed was this Youtube video (although it seems basic, I was unaware how to do server programming at all). I can provide some of my attempts if I still have it. The server is set up towards the end of the playlist.

答:
if you want to create one server client application , the put your game logic on server , and GUI , you distribute over clients.
Don't put your logic code , visibility code to GUI Client application.
Also create one object of your shared game data and multiple objects of the clients.  are you getting m</p>

Title: Separate GUI for clients


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
The thing to keep in mind while choosing a language, is what benefit you will get from using it, and how long it will take to get it.

The main idea between languages like python and perl is to do more with less man time, but with more cpu time. In fact you will spend more time coding a python or perl script than it will be executed, but you get my point.

The advantage of C/C++ is that they are fast, but at a cost of syntax and strong typing: you have to do a lot of thing yourself so that the computer has not to choose it at compile time.

When you make a code, some lines will be ran a lot more than others, and those lines are the one that pose a problem. On the other hand, all the rest of the code, the one you spent a lot of time on, is executed much much less often.
You might have heard it, but it is the infamous 80/20 rule, and you won't be able to bypass such rule.

The solution to this problem, is to use an easier language (by easier I mean more developer friendly: less typing, lazy interpretation, a lot of preexisting routines and stuff, etc.) to do all your code.

You will do it so quickly compared to if you would have done it with C or C++, it would have taken much more brain ache.

Your program will be slow, but with a profiler, you isolate the part which are ran 80% of the time, and you do them with C or C++.

By prorgamming this way, you saved a lot of time, and your program is as efficient, as much fast, has much less chances to leak memory, and you saved time.

Scripting languages were designed to be on the side of the developer, but optimisation is still possible. Of course you can be a design pattern magician or a STL voodoo or even a lisp warrior, and maybe an haskell monk. But languages makes us talk to computers, languages are not made for us to BE computers !


问:
How to understand if a property is a member of a class or I have to create a different class that holds it?
Sometimes when you create a class you can add there several properties (new data members) that you are not certain if you want to do or not. For example, I have a casino slots game. I have tiles and tiles are spinning on different reels. So once 3 tiles come on the same line then player wins 3$, 4 tiles - 4$ and 5 tiles - 5$ for tile A and for tile B player wins 5$, 10$, 20$ accordingly. Should, for example, each tile store the data of its reward or there should be a reward manager for checking how many tiles are consecutive next to each other to give the reward to the player?

Please note that I don't want to have such a situation. But I find me many times thinking "Should I add this data, and consequently, corresponding logic the my class or not?". I worry about single responsibility principle when I want to have different managers for such things, but on the other hand I came to a situation to create several singletons or singleton-like classes.

答:
Classes are often used for concepts, to hold together all the attributes of the concept and the interactions that are possible.

When deciding what to do however, it's purely a matter of what works best, and what design is the best. When you are deciding what to do I'd go about it this way: If the calculation is part of the (to be) object, make a class for it. If not, don't. Of course there will be unclear decisions (player.paint() or paint(player)), but it works as a general guideline. Also take into account the clutter you can create by keeping things unorganized.

For example: Let's say we have a car. This car has wheels, a driver, passengers, and cargo. What we want to do is associate the wheels, driver, passengers and cargo with the car, so we make the car into a class with all those things, possibly just pointers to the actual objects.

Now let's say we have a world of which there is only one in the entire program. Distances will be measured without reference to a World class or object. This is because the world, at least in this case, is not really a collection of attributes. Even if is had a maximum size, we would not necessarily define it as a class, because there is not much use for it, there would be more clutter because of it, and it isn't really useful for anything.

There are of course also examples where it's hard to decide. If we have a lot of trees we could store tuples of x and y coordinates in a collection called trees. However, we could also make a Tree class and store our info in there. Whether you should do that or not comes down to the following:

Will you be giving them extra methods like paint, update, grow and so forth?

Will they be objects with a lot of extra attributes that you want to keep together? Like size, age, shape, and so forth?


问:
How to smooth out a diagram?
we have a data set that creates a graph, it works but the graph has many up and downs and looks really bad,

what I like to know if there is a known technique or algorithm or even an API that can smooth it out.

a very bad drawing of mine is demonstrated, so what I like to do is to get from A to B

I hope the picture below is able to represent what I try to achieve :/.

I apologies for the used tag, I'm not quite sure how to classify this question.

答:
There are certainly a lot of algorithms for this. Probably the simplest one would be to change the value at every point to the average within x datapoints in the original.

Maybe not the best quality answer, but you can literally just choose from a list here:
https://en.wikipedia.org/wiki/Smoothing#Smoothing_algorithms

Title: How to smooth out a diagram?


答:
In general, when you are doing object oriented programming, you want your data and behavior to be together (in one class).

You also want to achieve high cohesion with your classes. This means that most/all of your methods use most/all of the attributes in your class. This will help you achieve the single responsibility principle. Low cohesion means that part of your data is not being used when certain actions are taken (meaning it is not related to the action, meaning it probably should not be in the same class). Following these principles will create many small but focused classes.

In general you should always be able to state what your class does in a single sentence without using the word 'and'. If you cannot do this, your class is probably doing too much.

Title: How to understand if a property is a member of a class or I have to create a different class that holds it?

Body:
Sometimes when you create a class you can add there several properties (new data members) that you are not certain if you want to do or not. For example, I have a casino slots game. I have tiles and tiles are spinning on different reels. So once 3 tiles come on the same line then player wins 3$, 4 tiles - 4$ and 5 tiles - 5$ for tile A and for tile B player wins 5$, 10$, 20$ accordingly. Should, for example, each tile store the data of its reward or there should be a reward manager for checking how many tiles are consecutive next to each other to give the reward to the player?

Please note that I don't want to have such a situation. But I find me many times thinking "Should I add this data, and consequently, corresponding logic the my class or not?". I worry about single responsibility principle when I want to have different managers for such things, but on the other hand I came to a situation to create several singletons or singleton-like classes.


答:
Might be way off here, but this is how I feel about WebApps and working with [complex] remote API's in many cases:

I would make it a class (ie, a library of data mitigate methods) instead of model (ie, stack of data mitigate functions). It seems like it would act more transparent, more logic/schema agnostic, and you could use it wherever without loading->calling a model/controller itself each time you want to use it. The logic is still separated, the datapoint is still flexible, and it seems more open for interoperability in strange cases like stacking clientAJAX->appJSON->appLIB->remoteAPI->remoteJSON etc to poll the endpoint indirectly.


答:
Is there a reason to use C++?  Certainly.

Some people might simply prefer using C++ over other options.  Asking if there's a reason to use C++ is like asking why we need to have hundreds of flavors of ice cream.  Not everyone likes simply sticking with Vanilla.

If developers already are very competent with C++, the question for them may not be 'why use it?', but rather 'why not?'.  There seems to be this trendy anti-C++ thing going on in SO right now, but believe it or not, not everyone subscribes to that.  Some people may simply like C++ better than the other languages.

Does C++ need to be used for apps?  Of course not.  But this same exact question can also be asked for any other language.  There are very, very few cases where a particular languages needs to be used for an application.

Title: Is there any reason to use C++ instead of C, Perl, Python, etc.?

Body:
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?


问:
How to keep code examples in javadocs up to date
I'm working on a small library that provides implementations of basic, well known string metrics. Mostly for my own education. So development happens whenever I've got a bit of spare time.

Because of this I've automated most processes so I can release a version as often as I work on it without too much effort. However maintaining the Java doc is still a burden because it includes examples.

As the API evolves I manually have to check each example over and over again. Is there a better way to do this?

I have considered moving the documentation and examples into a separate project (e.g. Caliper Tutorial) so it can be re-factored and compiled along with the regular code. However that does move the documentation away from the class it is about.

So yeah. I'd like to have my cake and eat it too. :D

```<code> * <h2>Tokenization</h2>
 *
 * Tokenization cuts up a string into tokens e.g.
 * <code>chilperic ii son of childeric ii</code> is tokenized into
 * <code>[chilperic, ii, son, of,
 * childeric, ii]</code>. Tokenization can also be done repeatedly by tokenizing
 * the individual tokens e.g.
 * <code>[ch,hi,il,il,lp,pe,er,ri,ic, ii, so,on, of, ch,hi,il,ld,de,er,ri,ic, ii]</code>
 * <p>
 *
 * ```
 *
 * {@code
 *  return new StringMetricBuilder()
 *          .with(new SimonWhite<String>())
 *          .tokenize(new Whitespace())
 *          .tokenize(new QGram(2))
 *          .build();
 * }
 *
 * ```
 *
 * <p>
</code>```

If the above it too abstract. This is a sample of documentation. Currently I'm adding static constructors as advised by Effective Java e.g. Tokenizers.createQGram(2) while depreciating the constructor method. Each time I do something like this, I'd have to update the example code above and check if it still works.

答:
This might not answer your question - depending on how much of a 'requirement' it is to have these examples in your documentation.

Perhaps you could do a different angle: Provide examples in your JUnit tests.  (Perhaps even a package like com.examples)  The problem with code in comments is that your IDE is going to ignore it, for the most part.  But your IDE will validate the code in your JUnit tests.  By doing this, you ensure the code examples are 'correct' - the tests will either not compile or simply fail if you haven't updated them.

I'm not a wizard with Javadocs, but there might be a way to link your source file's documentation to the JUnit file with the example code in it.  I really wouldn't know where to begin on this though.  A cursory googling showed me the @see tag.  I tested it in a project but haven't tested it in an actual javadoc after it was generated.

This would definitely require a bit of research up-front, but I really think you'd be better off in the long run if your code examples were actually being compiled.

As a stretch-goal, you could also add in code coverage when running your JUnit examples.  This way you would know at-a-glance how much of your code base is covered by your examples.


问:
Should I have a separate XML settings file for my application?
I want to be able to add some objects to my application by simply adding a XML node to a config file. Should I put it in the app.config file or should I make a separate XML config file? A node would look something like this

```<code><Books>
   <Book>
     <title></title>
     <author></author>
   </Book>
</Books>
</code>```

In that case I would add multiple books to my application by adding them in the config file. Is it bad practice to have 2 config files? I tried googling for solutions about the app.config file but it seems to not be the place to do it.

答:
Most likely, you want a separate file. App.config is for application configuration, whereas what you are specifying is data.

Your data store could eventually become a database or json, or whatever else. Keeping it separate will make moving to something else easier in the future.


问:
Null values handling in big scale applications
Tl;dr: Should we return null and not know origins of the error or throw exceptions and handle them appropriately?

A few years ago I found this article: http://stackify.com/golden-rule-programming/

It says:

```<code>If it can be null, it will be null
</code>```

This kind of thinking leads to defensive programming throughout the application, tons of ifnulls everywhere and in theory SHOULD never get a NullReferenceException and be more efficient compared to throwing exceptions everywhere if null is encountered.

On the other hand, if we return null in all layers of the application, we cannot know for sure where did the null value originate from.

The opposite is when throwing exceptions, because we can know origin of the error for sure.

Returning null value everywhere can come from data layer, from the database, it can even be business logic trying to make sense of data and failing to do so... Basically, it can be anything.

Therefore, I see two (or three) camps:

If it can be null, it should be null

Throw exceptions everywhere, if you encounter null value, where it is not anticipated

Mix the first two

Forehand, I think 3. Mixing the first two leads to a less predictable system and therefore slower pace of development, which is not something we want, right?

Using the 1. one leads to not knowing where did the null came from, but it is more efficient way to handle a big load (billions of requests).

The 2. is not as efficient performance wise, but is more verbose when diagnosing errors, by just looking at the logs or debugging.

The question itself is really conceptual and the answer I would like to get would be based on experience working with big scale applications. Really looking forward to what you think :)

答:
You are mixing stuff.

If it can be null, it will be null

That means that any value/object that can be null your code needs to deal with gracefully.

Three camps?  Not know where it came from?  Wrong.

There is one camp:  test for null for any nullable type and deal with it gracefully. If null is not valid you throw an exception and yes you know exactly where the exception came from as the exception has a source.  You don't pass the null on to the next layer if it is not valid and lose where null came from.

At the data layer if null is valid but it means 0 you just assign a 0 to a non-nullable type and be done with it. At the point it is a non-nullable type you no longer need to test null.

Reference types are typically nullable and need to be tested every time.

In most if not all environments value type of decimal cannot be null so you don't need to test for null.


答:
To get you started, you should start reading about Moving Average which is the simplest smoothing method and is being applied to many fields outside signal processing because its explanation is perhaps the most understandable to everyone not having signal processing backgrounds.

In particular, all of the Moving Average methods belong to causal systems, which means these smoothing methods do not try to use tomorrow's data to calculate a smoothed value for today.

However, if you have access to the entire time series (from historical data), then there is nothing to prevent you from using non-causal smoothing methods to calculate what you need.

(Aside from moving average, there is also another family of methods called "auto-regression", but it is often more used on physical systems, not artificial human-created systems such as economics and stock markets.)

Title: How to smooth out a diagram?

Body:
we have a data set that creates a graph, it works but the graph has many up and downs and looks really bad,

what I like to know if there is a known technique or algorithm or even an API that can smooth it out.

a very bad drawing of mine is demonstrated, so what I like to do is to get from A to B

I hope the picture below is able to represent what I try to achieve :/.

I apologies for the used tag, I'm not quite sure how to classify this question.


答:
You can make a window function that takes weighted samples of adjacent elements and creates a second, smoother data set.  There are several popular ones.  Triangle, square (flat), Hann, Hamming, Blackman, Gaussian, etc.  Quite a few resemble a bell curve.  Each has a different effect on the signal.  The individual sample weights will always equal 1 so your average amplitude isn't effected.

You can then adjust the width (number of adjacent samples) to increase or decrease smoothing effect.  I.e. start with 5 total samples (-2 ... +2).  The wider the sample area, the smoother the graph.

https://en.wikipedia.org/wiki/Window_function

This isn't very hard to program or setup in something like Excel.

Title: How to smooth out a diagram?


问:
How to watch a message queue properly
I have a scenario where I need to 'watch' an Amazon queue. When a message arrives I need to get this message and process it.

Right now this is implemented with a do/while and Thread.Sleep when no messages is found. It's working but I would like to know if there is a better approach, possibly with a design pattern or something.

The actual code:

```<code>      do
        {
            try
            {
                var message = _queue.GetMessage();
                if (message == null)
                {
                    Thread.Sleep(100000);
                    continue;
                }
                else
                //process message
             }
        } while(true)
</code>```

答:
This is a very similar approach I've take using Amazon SQS, with a few differences to overcome a few potential downsides;

if a message becomes available just after you check, you'll be
waiting 100 seconds before taking another peek, which is not
particularly responsive.

If many messages arrive in quick
succession, you may not be able to keep up with them using this same
thread to process them as retrieve them.

If an exception occurs,
you may be thrown out of the loop and no more messages will be
processed, ever.

None of these things are difficult to overcome though:

as mentioned in the comments, Long Polling is a (brief) blocking call
which will return very quickly as soon as a message arrives (or still
return null if no message arrives within the timeout - which is a
maximum of 20 seconds.)

You can retrieve up to 10 messages in a single call, and these can be
handed off to a thread pool to process them and keep this thread
looking for more work/messages.

try/catch within the loop. I'm sure you had this covered already and
were just providing the outline!

Title: How to watch a message queue properly


答:
I think you are missing several other options. For example, you could use a language which doesn't have null. Haskell, Ruby, Smalltalk, many others simply don't have null references, so the problem doesn't even arise.

Another option would be to use a language which does have null but has explicit null tracking that allows you to statically ensure that you can never have null references. Spec# does that, for example.

A variant of that option is to use a language which doesn't have null tracking, but use an external static analyzer, maybe aided by annotations. Code Contracts.NET (an offshoot of Spec#) does that, for example.

Yet another option is to encapsulate the notion of nullness into a type. One of the problems with null references is that null references are really overloaded. What does getting a null mean? Some things are meant to fail, e.g. parsers, or looking up a key in a dictionary. It is normal for parsers to be handed invalid input, it is normal to not find a key in a dictionary, that's not an error, and not an exceptional situation.

For this latter case, you can use an Option type. An Option is basically kind-of like a collection that is either empty or has exactly one element. (This analogy is actually pretty profound as we shall see shortly.) In the case of the dictionary example, a Dictionary<K, V> would have a method Option<V> get(K key) which returns either a "filled" Option with the value, if the key exists, or an "empty" Option if the key doesn't exist. The important thing is that the type system can ensure that you have to deal with both cases in your code.

Except that you often actually don't have to deal with both cases. That's where the analogy to collections comes in: an Option is isomorphic to a list / an array / an iterator / a stream / an IEnumerable / some other kind of collection which is either empty or holds exactly one value. This means that Option can implement whatever collections interfaces your language has, can be a member of the collections framework and can be used with all the collections methods. For example, if you want to transform the value, then you don't need to actually get the value out of the Option. All collections frameworks have a method to apply a transformation function to every element of the collection (map in most languages, collect in Smalltalk, Objective-C and Ruby, select in SQL and .NET, transform in C++). What does map do when you call it on an empty collection? It returns an empty collection. And on a non-empty collection it will return another collection with each element (or in this case the only element) transformed. You don't even have to check whether or not your Option is empty, you can just call map on it, and it will do the right thing.

You can chain multiple maps. You can use flatMap (SelectMany in .NET) to chain the use of Options. You can use fold (aka reduce, aggregate, accumulate) to get the value out or alternatively supply a default. And so on.

Apart from being a collection, Option is also a monad, this makes it easy to work with in languages that have special syntactic support for monadic operations (e.g. Haskell's do-notation, Scala's for-comprehensions, C#'s and VB.NET's LINQ query comprehensions).

In Haskell, it is called Maybe a and has two data constructors called Just a and Nothing. (If you are a Java person read Maybe<T> and Just<T> and think of data constructors as final subclasses.) In Scala, it is called Option[T] and has two subclasses Some[T] and None. Even Java has one, it is called Optional<T>.

Obviously, there is a difference between a language like Haskell, which doesn't have null in the first place, and a language like Java, where Optional<T> is an afterthought. In the first case, nulls cannot happen, period. In the second case, I would treat null like any other kind of invalid data: intercept it at the outer boundary of your system, and either throw an exception or sanitize it into an Optional<T>. (The really nasty thing about a language like Java is of course that a field of type Optional<T> may itself be null.)

In Scala, for example, null mainly exists for compatibility reasons. Pretty much the only way that you can end up with a null from the Scala language, is with a declared but not initialized mutable field. However, mutable fields are rarely used in Scala, and very un-idiomatic. No method in the Scala library will ever return null. Idiomatic Scala code will never return null. Usually, the only way to end up with null is by calling Java code, and that is typically handled the way I described above: you have a Scala wrapper for the Java code which handles all potential nulls and the rest of the code uses that Scala abstraction and doesn't bother with null at all.

Yet another option that is however not applicable in all cases is to use a special "empty" object to denote the absence of data instead of null. A dummy user account for a User field, an empty string for a String field, an empty list for a List field and so on.

Title: Null values handling in big scale applications

Body:
Tl;dr: Should we return null and not know origins of the error or throw exceptions and handle them appropriately?

A few years ago I found this article: http://stackify.com/golden-rule-programming/

It says:

```<code>If it can be null, it will be null
</code>```

This kind of thinking leads to defensive programming throughout the application, tons of ifnulls everywhere and in theory SHOULD never get a NullReferenceException and be more efficient compared to throwing exceptions everywhere if null is encountered.

On the other hand, if we return null in all layers of the application, we cannot know for sure where did the null value originate from.

The opposite is when throwing exceptions, because we can know origin of the error for sure.

Returning null value everywhere can come from data layer, from the database, it can even be business logic trying to make sense of data and failing to do so... Basically, it can be anything.

Therefore, I see two (or three) camps:

If it can be null, it should be null

Throw exceptions everywhere, if you encounter null value, where it is not anticipated

Mix the first two

Forehand, I think 3. Mixing the first two leads to a less predictable system and therefore slower pace of development, which is not something we want, right?

Using the 1. one leads to not knowing where did the null came from, but it is more efficient way to handle a big load (billions of requests).

The 2. is not as efficient performance wise, but is more verbose when diagnosing errors, by just looking at the logs or debugging.

The question itself is really conceptual and the answer I would like to get would be based on experience working with big scale applications. Really looking forward to what you think :)


答:
One can look at state from three points:

The state-space the underlying machine provides.

The state-space the language provides.

The state-space the program-logic allows.

In "safe" languages, the first one can generally be disregarded. Though it's good for things like boolean values that are neither true nor false.

Haskell for example allows you to restrict most variables state-space to their program-logic space, while many others like Java make just about everything nullable, even if it logically isn't.

Thus you must handle it appropriately for each case.

Luckily, in "safe" languages you don't have to write most null-checks manually, the language throws an exception for you if you just use it.