问:
Making a safe PHP login system
I am making a php website that requires user login. It has a remember me function. I would like to ask if the following approach is safe ?

User logs in with correct username and pass (and remember me option).

I will get his userID , hash it , and save that string in a cookie against some key , like 'usercookie'

I would like to know if this is safe. If not , what is the best way to do this ?

答:
To start off with your login, I'd like to say that the password should be stored safely as well(This is probably not your main concern).

Whenever you use sessions or cookies, you're vulnerable to session hijacking.
Now on that link, there are ways to prevent session hijacking as well.

Like:

Encryption of the data traffic passed between the parties by using SSL/TLS; in particular the session key (though ideally all traffic for the entire session). This technique is widely relied-upon by web-based banks and other e-commerce services, because it completely prevents sniffing-style attacks. However, it could still be possible to perform some other kind of session hijack.

Use of a long random number or string as the session key. This reduces
  the risk that an attacker could simply guess a valid session key
  through trial and error or brute force attacks

So it's not 100% secure.
There are more ways to prevent it.

Title: Making a safe PHP login system


问:
Complex iterators in C
note: this was originally asked on SO.

Part of my current project involves iterating over sequences that don't necessarily exist. For example, I have something similar to a relational database in memory, so say I have three arrays

```<code>typedef struct { size_t car_index, size_t part_index } car_part_t;

car_ * cars;
part_t * parts;
car_part * car_parts;
</code>```

I want to be able to iterate over all the parts in a given car, for example. I specifically want the part and not the car_part. My current solution is

```<code>typedef struct {
    size_t car_index;
    size_t part_index;
    size_t m_car_part_index; // keeps progress
} car_part_iterator_t;
</code>```

and to have two functions

```<code>car_part_iterator_t car_part_first(size_t car_index);
</code>```

which returns an iterator set up such that it.part_index is the index of the part in parts, it.car_index is the car selected by the first parameter, and it.m_car_part_index is a 'private' variable used to track progress in the car_parts list.

I then have a similar function for getting the next one

```<code>bool car_part_next(car_part_iterator_t * it);
</code>```

which moves to the next car part, and returns if the iterator is still valid. Finally for completeness I have

```<code>bool car_part_valid(car_part_iterator it);
</code>```

to check if the current iterator is still valid. So it can be used in a for loop like

```<code>for (car_part_iterator_t it = car_part_first(car_index);
    car_part_valid(it); car_part_next(&it))
{
    // use it.part_index ...
}
</code>```

To me, this sounds like a good solution that I came to after some trial and error. I also experimented with a function that returns an iterator before the first result, so the next` function would return the first result, for use in while loops.

Is this a good pattern? I assume a known one. Does it have a name? Are there pitfalls I'm not seeing?

notes:

On SO the generality of this was questioned (ie it can be made more general), but as it stands I'm not too bothered about that.

It was also pointed out that the valid function isn't strictly needed for the loop, but it allows for a more natural for loop, and is also sometimes useful outside of loops.

答:
Is this a good pattern?

Yes, in general.

I can't see how it interacts with your data in detail, but it works well in lots of places, and is probably fine here too.

I assume a known one. Does it have a name?

It's just the iterator pattern. It may be more complex than a linked-list or array iterator, but it's not so obviously different to a tree iterator.

Are there pitfalls I'm not seeing?

Well, your current implementation seems to depend on global state. Generalizing this aspect is probably a good idea.

Lastly, when you said the sequence might not exist, I was expecting to see an iterator lazily generating the values. Since that isn't the case here, what do you actually mean?

ContentLicense: CC BY-SA 3.0

Title: Complex iterators in C


问:
Is a private property the same as a public field?
Will a private property same as a public field? Here is the sample code I wrote to understand this:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetSet
{
    class Program
    {
        private int Age_private { get; set; }
        public int Age_public;
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Age_public = 5;
            p.Age_private = 10;  // calling set
            int m = p.Age_public;
            int n = p.Age_private; // calling get
            Console.WriteLine(m);
            Console.WriteLine(n);
            Console.ReadLine();
        }
    }
}
</code>```

Am I doing this correctly?

Also, does it follow that a public field will never require a getter and setter?

Reference: When are Getters and Setters Justified

答:
Am I doing this correctly?

No. The idea of properties is that the property itself is public and provides access to private fields. Your example however does the opposit by declaring the property private while the field is exposed public.

What it should look like:

```<code>class Program
{
    private int Age_private;    //private field, not visible outside of class
    public int Age_public
    {      //public property to manage access to age
        get { return Age_private; }
        set
        {
            if (value == Age_private + 1)
            {
                Age_private = Age_private + 1;
            }
        }
    }
    public Program()
    {
        Age_private = 0;
    }

    static void Main(string[] args)
    {
        Program p = new Program();
        p.Age_public = 1;     //increment age using setter
        int m = p.Age_public;        //get age from getter
        Console.WriteLine(m);
        p.Age_public = 2;     //increment age again using setter
        m = p.Age_public;
        Console.WriteLine(m);
        p.Age_public = 5;     //use setter with invalid value
        m = p.Age_public;
        Console.WriteLine(m);    //age is unchanged because setter didn't change the private field
        p.Age_public = -50;     //use setter with invalid value
        m = p.Age_public;
        Console.WriteLine(m);    //age is still unchanged because setter didn't change the private field
        Console.ReadLine();
    }
}
</code>```

DO NOT: expose fields outside of the class

DO: provide appropriate methods/properties to access fields where needed

note that the setter of the property only allows to increase the age by one as suggested in the answer you referenced. A property without logic would again be subject to the answer you referenced  because it exposes the field without any control those breaking encapsulation again.

Body:
Am I doing this correctly?

No. The idea of properties is that the property itself is public and provides access to private fields. Your example however does the opposit by declaring the property private while the field is exposed public.

What it should look like:

class Program
{
    private int Age_private;    //private field, not visible outside of class
    public int Age_public
    {      //public property to manage access to age
        get { return Age_private; }
        set
        {
            if (value == Age_private + 1)
            {
                Age_private = Age_private + 1;
            }
        }
    }
    public Program()
    {
        Age_private = 0;
    }

    static void Main(string[] args)
    {
        Program p = new Program();
        p.Age_public = 1;     //increment age using setter
        int m = p.Age_public;        //get age from getter
        Console.WriteLine(m);
        p.Age_public = 2;     //increment age again using setter
        m = p.Age_public;
        Console.WriteLine(m);
        p.Age_public = 5;     //use setter with invalid value
        m = p.Age_public;
        Console.WriteLine(m);    //age is unchanged because setter didn't change the private field
        p.Age_public = -50;     //use setter with invalid value
        m = p.Age_public;
        Console.WriteLine(m);    //age is still unchanged because setter didn't change the private field
        Console.ReadLine();
    }
}

DO NOT: expose fields outside of the class

DO: provide appropriate methods/properties to access fields where needed

note that the setter of the property only allows to increase the age by one as suggested in the answer you referenced. A property without logic would again be subject to the answer you referenced  because it exposes the field without any control those breaking encapsulation again.


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答:
I like regular expressions in general I find them easier to read/understand than the 20 lines of code I would have to replace them with. Short regular expressions are quickly read and understood and they are relatively easy to maintain (if the expression changes you only have one line to change versus looking through the 20 lines of code to make the change). There are times where they are misused but so are many other things.

The reason you probably see so much abuse of them is because your browsing the PHP section of StackOverFlow as I am sure you are aware there are a lot of umm immature PHP programmers out there.

ContentLicense: CC BY-SA 2.5


问:
Constructor Injection vs. IocFactory
Today at work a collegue and I had a discussion about the following:

Basically we have a rule engine which works in the following way:

RuleExecutor

Gets all rules to execute in the constructor like public RuleExecutor(ICollection<IRule> rulesToExecute) { ... }

Executes all rules by calling rule.ApplyRule(); for each rulesToExecute

Rules

Provide method ApplyRule(); which executes the rule

Now we want the RuleExecutor to be executed in a cron job.

We had a discussion about how to retrieve an instance of the RuleExecutor.

I think the "correct way" is via constructor injection

```<code>public RuleCronJob(IRuleExecutor ruleExecutor) { ... }
</code>```

My collegue wants to use a "IocFactory" which has a static method GetInstance<>.
So in the "execute method" of the cron job he would do something like var ruleExecutor = IocFactory.GetInstance<IRuleExecutor>();

```<code>public static TType GetInstance<TType>(params Tuple<string, object>[] constructorParameters)
    {
        if (constructorParameters.Any())
        {
            var constructorArgs = new Collection<ConstructorArgument>();
            foreach (var parameter in constructorParameters)
            {
                constructorArgs.Add(new ConstructorArgument(parameter.Item1, parameter.Item2, true));
            }

            return Kernel.Value.Get<TType>(constructorArgs.Cast<IParameter>().ToArray());
        }

        return Kernel.Value.Get<TType>();
    }
</code>```

Kernel is a StandardKernel of Ninject.

I think the constructor injection is better because it allows for easier tests (mocking) etc. but I couln't convince him to use it because he thinks that the IocFactory "works as well so why not use it"...

What would be some arguments to convince him to use constructor injection instead of the IocFactory?

答:
Well, for a start, the IOCFactory, or rather the way you described it being used, is a bold-faced lie, because it involves no inversion of control. If you continue calling getInstance() yourself, you should a least rename the alleged IOCFactory.

As Ben Aaronson pointed out, a container without inversion of control is just a Service Locator. A lot has been written about Dependency Injection vs. Service Locators, over ten years ago by Martin Fowler on his blog, or five years ago on stackoverflow:
https://stackoverflow.com/questions/1557781/whats-the-difference-between-the-dependency-injection-and-service-locator-patte

Title: Constructor Injection vs. IocFactory


问:
Find the new coordinates using a starting point, a distance, and an angle
Okay, say I have a point coordinate.

```<code>var coordinate = { x: 10, y: 20 };
</code>```

Now I also have a distance and an angle.

```<code>var distance = 20;
var angle = 72;
</code>```

The problem I am trying to solve is, if I want to travel 20 points in the direction of angle from the starting coordinate, how can I find what my new coordinates will be?

I know the answer involves things like sine/cosine, because I used to know how to do this, but I have since forgotten the formula. Can anyone help?

答:
Just to record a javascript adaptation from Movable Type Scripts</p>

```<code>function createCoord(coord, bearing, distance){
    /** http://www.movable-type.co.uk/scripts/latlong.html
     φ is latitude, λ is longitude,
     θ is the bearing (clockwise from north),
     δ is the angular distance d/R;
     d being the distance travelled, R the earth’s radius*
     **/

    var
        radius = 6371e3, //meters
        δ = Number(distance) / radius, // angular distance in radians
        θ = Number(bearing).toRad();
        φ1 = coord[1].toRad(),
        λ1 = coord[0].toRad();

    var φ2 = Math.asin(Math.sin(φ1)*Math.cos(δ) + Math.cos(φ1)*Math.sin(δ)*Math.cos(θ));

    var λ2 = λ1 + Math.atan2(Math.sin(θ)*Math.sin(δ)*Math.cos(φ1), Math.cos(δ)-Math.sin(φ1)*Math.sin(φ2));

    λ2 = (λ2+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180°

    return [λ2.toDeg(), φ2.toDeg()]; //[lon, lat]
}

Number.prototype.toDeg = function() { return this * 180 / Math.PI; }
Number.prototype.toRad = function() { return this * Math.PI / 180; }
</code>```

Body:
Just to record a javascript adaptation from Movable Type Scripts

function createCoord(coord, bearing, distance){
    /** http://www.movable-type.co.uk/scripts/latlong.html
     φ is latitude, λ is longitude,
     θ is the bearing (clockwise from north),
     δ is the angular distance d/R;
     d being the distance travelled, R the earth’s radius*
     **/

    var
        radius = 6371e3, //meters
        δ = Number(distance) / radius, // angular distance in radians
        θ = Number(bearing).toRad();
        φ1 = coord[1].toRad(),
        λ1 = coord[0].toRad();

    var φ2 = Math.asin(Math.sin(φ1)*Math.cos(δ) + Math.cos(φ1)*Math.sin(δ)*Math.cos(θ));

    var λ2 = λ1 + Math.atan2(Math.sin(θ)*Math.sin(δ)*Math.cos(φ1), Math.cos(δ)-Math.sin(φ1)*Math.sin(φ2));

    λ2 = (λ2+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180°

    return [λ2.toDeg(), φ2.toDeg()]; //[lon, lat]
}

Number.prototype.toDeg = function() { return this * 180 / Math.PI; }
Number.prototype.toRad = function() { return this * Math.PI / 180; }


答:
The simple way to explain your question regard private and public is; private stands for privacy and public stand for spotlight.

When you declare a private field or method your intention is to make it visible to where its declares only, outside of the form or class is impossible to.

Title: Is a private property the same as a public field?

Body:
Will a private property same as a public field? Here is the sample code I wrote to understand this:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetSet
{
    class Program
    {
        private int Age_private { get; set; }
        public int Age_public;
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Age_public = 5;
            p.Age_private = 10;  // calling set
            int m = p.Age_public;
            int n = p.Age_private; // calling get
            Console.WriteLine(m);
            Console.WriteLine(n);
            Console.ReadLine();
        }
    }
}
</code>```

Am I doing this correctly?

Also, does it follow that a public field will never require a getter and setter?

Reference: When are Getters and Setters Justified


问:
Best practice boolean assignment
I came across the following conditional in a program that I have taken over from another developer:

```<code>if (obj.Performance <= LOW_PERFORMANCE)
{
    obj.NeedsChange = true;
}
else
{
    obj.NeedsChange = false;
}
</code>```

I believe this code is redundant and ugly, so I changed it to what I thought was a simple boolean assignment based on a comparison:

```<code>obj.NeedsChange = obj.Performance <= LOW_PERFORMANCE;
</code>```

Upon seeing this, someone reviewing my code commented that although my change is functionally correct, it might confuse someone else looking at it.  He believes that using a ternary operator makes this assignment more clear, whereas I don't like the addition of more redundant code:

```<code>obj.NeedsChange = (obj.Performance <= LOW_PERFORMANCE) ? true : false;
</code>```

His reasoning is that doing something in the most concise way is not worth it, if it causes another developer to have to stop and puzzle out exactly what you've done.

The real question here is which of these three methods of assigning a value to the boolean obj.NeedsChange is the most clear and the most maintainable?

答:
Variant 1 is easily understood, but that is its only advantage. I automatically assume that anyone who writes like this doesn't really understand what booleans are all about, and will be writing similarly infantile code in many other respects.

Variant 2 is what I would always write, and expect to read. I think that anyone who is confused by that idiom shouldn't be a professional writer of software.

Variant 3 combines the disadvantages of both 1 and 2. 'nuff said.

Title: Best practice boolean assignment


答:
Anytime code is more complicated than it needs to be triggers a "what is this supposed to be doing?" smell in the reader.

For example, the first example makes me wonder, "was there other functionality in the if/else statement at some point that was removed?"

Example (2) is simple, clear, and does exactly what is needed. I read it and immediately understand what the code does.

The extra fluff in (3) would cause me to wonder why the author wrote it that way instead of (2). There should be a reason, but in this case there doesn't seem to be, so it's not helpful at all and harder to read because the syntax suggests something present which is not there. Trying to learn what is present (when nothing is) makes code harder to read.

Title: Best practice boolean assignment

Body:
I came across the following conditional in a program that I have taken over from another developer:

```<code>if (obj.Performance <= LOW_PERFORMANCE)
{
    obj.NeedsChange = true;
}
else
{
    obj.NeedsChange = false;
}
</code>```

I believe this code is redundant and ugly, so I changed it to what I thought was a simple boolean assignment based on a comparison:

```<code>obj.NeedsChange = obj.Performance <= LOW_PERFORMANCE;
</code>```

Upon seeing this, someone reviewing my code commented that although my change is functionally correct, it might confuse someone else looking at it.  He believes that using a ternary operator makes this assignment more clear, whereas I don't like the addition of more redundant code:

```<code>obj.NeedsChange = (obj.Performance <= LOW_PERFORMANCE) ? true : false;
</code>```

His reasoning is that doing something in the most concise way is not worth it, if it causes another developer to have to stop and puzzle out exactly what you've done.

The real question here is which of these three methods of assigning a value to the boolean obj.NeedsChange is the most clear and the most maintainable?


问:
Best practices for tracking multiple pieces of data in a program
I have a project in C (don't ask why but it needs to be in C), where I need to track multiple pieces of data and commands for different modules. Some actions that the program will take depend on the interactions between these different pieces of data (eg. if foo == 3 and bar == 4 do X, otherwise do Y). Some of these pieces of data will be structs grouping together similar information, some will just be primitives.

I am wondering what the best way to implement this would be. Personally, I think that each piece of data should be its own variable like so:

```<code>static int module_state;
static M1_Data module_1_data;
static int last_m1_command;
static M2_Data module_2_data;
etc...
</code>```

One of my coworkers is suggesting instead that I manage everything in a super struct. His reasoning is that everything can be passed around at once if need be, and it will make it easier to track where everything is, rather than having a bunch of lose variable. His idea is for something like so:

```<code>struct{
int module_state;
M1_Data module_1_data;
int last_m1_command;
M2_Data module_2_data;
...
} SuperState;

static SuperState state
</code>```

I am not sure I agree with his reasoning. What would the preferred way to handle this, and what are the upsides/downsides of both methods other than the ones listed?

答:
Personally, I would rather use structures, but not one common, I would use one for each module instead, with the properties I need to "publish" for other modules to be able to use.

Simple global variables are more difficult to maintain.

Using a structure per module will get rid of unnecessary dependencies (data related to a single module, and only to that module, is in the same place) between modules, and a structure is easy to pass all in once by pointer.


答:
I prefer 2, but I might go for a small adjustment to it:

```<code>obj.NeedsChange = ( obj.Performance <= LOW_PERFORMANCE );
</code>```

To me the parentheses makes the line easier to parse and makes it clear at a glance that you are assigning the result of a comparison, and not performing a double assignment. I'm not sure why that is (as off-hand I can't think of a language where parentheses would actually prevent a double assignment), but if you must satisfy your reviewer then perhaps this will be an acceptable compromise.

Title: Best practice boolean assignment

Body:
I prefer 2, but I might go for a small adjustment to it:

obj.NeedsChange = ( obj.Performance <= LOW_PERFORMANCE );

To me the parentheses makes the line easier to parse and makes it clear at a glance that you are assigning the result of a comparison, and not performing a double assignment. I'm not sure why that is (as off-hand I can't think of a language where parentheses would actually prevent a double assignment), but if you must satisfy your reviewer then perhaps this will be an acceptable compromise.


问:
How do you judge if you're paid enough?
How do you evaluate how much you feel you ought to be paid as a junior programmer?</p>

答:
Am I paid enough?

Well. When you start asking yourself this question it often means you're not? but knowing you're not paid enough doesn't mean you should be getting more money anyway.

Hence a more important question is:

Should I be paid more based on my experience and skills?

Now that's a completely different question. This question you can't directly answer yourself.

Title: How do you judge if you're paid enough?


问:
Java & REST API: How do I check for duplicate before inserting record?
I am developing an application in Java to parse and upload records from a CSV to an online database, via a REST API.

While I know for sure that there are no duplicate records in each CSV file, I cannot be sure that each CSV file has only been processed once (*see clarification below), so I need to check for duplicates before inserting.

[CLARIFICATION] I cannot implement a solution by checking that each CSV file has only been processed once. The CSV files contain bank transaction records downloaded from a bank. Therefore I know that each individual CSV file does not contain duplicates. However, multiple CSV files could be downloaded for the same date range, or for overlapping date ranges, etc. - so I need to check for duplicates at the transaction level rather than the file level.

Unfortunately I have no control over the back-end database, and I can only use the methods available via the API. This means the usual solutions using SQL (e.g. this question) are not suitable.

Methods available from API (http://help.moneytrackin.com/index.php/REST_API):

listTransactions

editTransaction

insertTransaction

Methods available but probably not relevant:

listProjects

listWriteProjects

getBalance

getTags

newProject

deleteProject

listTagTransactions

deleteTransaction

listCurrencies

userData

It is not a huge database: only four columns, and a few thousand records.

It seems like my only option is to iterate over each record to be inserted and compare it to each record from the database:

```<code>get ListOfRecordsInDb from database using listRecords(). Store in HashMap,
    local database or similar data structure??

for each record to be inserted,
    iterate over ListOfRecordsInDb, checking none of them match
       the record to be inserted
    if no match found, insert record
</code>```

This seems very inefficient. Are there any other options? If not, what is the most efficient way to compare thousands of records, using Java?

Answers to comments/questions:

What happens if you call insertTransaction with a transaction that
  already exists? Does it duplicate it or does it fail?

The transaction is successfully inserted as a duplicate

Does the CSV file have an "id" column?

No. The available columns are Date, Description, Amount and Balance. The combination of these makes each record unique, so I could potentially create an ID based on these.

Does listRecords() allow pagination, or can it only return all of the
  records?

It only returns the records, in XML format.

答:
Considering you stated that it is about REST API, think that each call to the API will result in some network traffic, where latency and transfer time apply. So I would say the less calls to the API you make (store results in memory to search through), the better.

However, when you work with the API, you don't always have a choice: if the API itself is not well engineered, or not engineered for purposes like your in mind, you might have no choice but do as you stated.

Also, consider that a remote service (REST API) can be used concurrently by many users, which means that loading all the results in memory or local DB, to process them later, may cause issues because the remote data has changed in the meantime.

I'm afraid mine is not a proper answer to your question, as I believe that a proper answer can be only given providing that you first document well what are the API calls available, their inputs and outputs, but you can benefit from these few tips, I hope.


答:
That is relatively safe, providing that you use SSL (HTTPS, use ssllabs to check the security of your site), and you configure your cookie to be domain-specific, have an expiry date not too far in future and be "HTTP-only".

Use mcrypt for encryption (there's support for that in PHP) and the salt key should be reasonably long, and kept SECRET, or change for each cookie (this is a little more complicated).

Also, consider what is the sensitivity of the information you hold for the user, and assess what would be the worst consequences if someone has stolen your user's data.

By definition, a system is secure if the cost of hacking it is greater than the intrinsic value of the data that can be stolen. Use this rule as a discriminator for your security assessment, to determine if you should worry about some more advanced techniques, of if the ones listed above would be enough.

It is also worth mentioning that - if the mentioned above was not enough, you should probably NOT offer your users the "remember me" option: banks do not do that, for obvious reasons.

Title: Making a safe PHP login system

Body:
I am making a php website that requires user login. It has a remember me function. I would like to ask if the following approach is safe ?

User logs in with correct username and pass (and remember me option).

I will get his userID , hash it , and save that string in a cookie against some key , like 'usercookie'

I would like to know if this is safe. If not , what is the best way to do this ?


问:
Can't I just use all static methods?
What's the difference between the two UpdateSubject methods below? I felt using static methods is better if you just want to operate on the entities. In which situations should I go with non-static methods?

```<code>public class Subject
{
    public int Id {get; set;}
    public string Name { get; set; }

    public static bool UpdateSubject(Subject subject)
    {
        //Do something and return result
        return true;
    }
    public bool UpdateSubject()
    {
        //Do something on 'this' and return result
        return true;
    }
}
</code>```

I know I will be getting many kicks from the community for this really annoying question but I could not stop myself asking it.

Does this become impractical when dealing with inheritance?

Update:

Its happening at our work place now.
We are working on a 6 month asp.net web application with 5 developers. Our architect decided we use all static methods for all APIs. His reasoning being static methods are light weight and it benefits web applications by keeping server load down.

答:
in Java ...

Static methods are not overwritten but are hidden instead and so it would be a big difference (problem ?) in the case of extending the class.

On the other hand I noticed that Java programers have a tendency to think all HAS TO be object,without really to understand why, and I disagree.

Static should be used for code specific to the class.
Static does not work well with inheritance.

some good examples of use of static methods are independent functions with no side effects.

also see the keyword synchronized...

Title: Can't I just use all static methods?


答:
It is easy to see that Variant 2 and Variant 1 are related via a series of obvious and simple refactorings:

```<code>if (obj.Performance <= LOW_PERFORMANCE)
{
    obj.NeedsChange = true;
}
else
{
    obj.NeedsChange = false;
}
</code>```

Here, we have needless code duplication, we can factor out the assignment:

```<code>obj.NeedsChange = if (obj.Performance <= LOW_PERFORMANCE)
{
    true
}
else
{
    false
}
</code>```

or written more concisely:

```<code>obj.NeedsChange = if (obj.Performance <= LOW_PERFORMANCE) true else false
</code>```

Now, it should be immediately obvious that this will assign true if the condition is true and assign false if the condition is false, IOW it will simply assign the value of the condition, i.e. it is equivalent to

```<code>obj.NeedsChange = obj.Performance <= LOW_PERFORMANCE
</code>```

Variants 1 and 3 are typical rookie code written by someone who doesn't understand what the return value of a comparison is.

Title: Best practice boolean assignment

Body:
It is easy to see that Variant 2 and Variant 1 are related via a series of obvious and simple refactorings:

if (obj.Performance <= LOW_PERFORMANCE)
{
    obj.NeedsChange = true;
}
else
{
    obj.NeedsChange = false;
}

Here, we have needless code duplication, we can factor out the assignment:

obj.NeedsChange = if (obj.Performance <= LOW_PERFORMANCE)
{
    true
}
else
{
    false
}

or written more concisely:

obj.NeedsChange = if (obj.Performance <= LOW_PERFORMANCE) true else false

Now, it should be immediately obvious that this will assign true if the condition is true and assign false if the condition is false, IOW it will simply assign the value of the condition, i.e. it is equivalent to

obj.NeedsChange = obj.Performance <= LOW_PERFORMANCE

Variants 1 and 3 are typical rookie code written by someone who doesn't understand what the return value of a comparison is.


问:
Client-Side JavaScript Business Logic in .Net Solution Stack
Fellow developers on other teams I interface with seemingly question my judgement calls as they pertain to the placement of coded business logic in a .Net MVC/Knockout web application currently under development. Granted, these types of questions have far reaching implications as they pertain to high-level architectural design patterns but warrant a detailed analysis nonetheless.

For example, let’s say we have a chunk of code that pulls data from a database, runs some calculation and then validates it against some user input. The argument consistently raised is such that the layers outside of the client browser (depicted below) should simply facilitate activities such as storing and passing data, security and other such activities that fall outside of implementing business logic. Then, within the browser, business rule validation and implementation.

[Client Browser/JS] <=> REST <=> [IIS/.Net MVC] <=> WCF/SQL <=> [WCF Endpoints & Databases]

Granted, there are numerous client-side JavaScript frameworks do promote this type of implementation pattern but I believe the intent with these assumes that the business rules and processes will always be executed client-side. Said another way; coupled to the browser.

In my particular circumstance I’ve come up with a few arguments against such an architecture and I want to make sure I’m not missing anything or being misleading.

Testing: While we can leverage testing frameworks such as Jasmine the level of effort involved with developing and integrating these types of test scripts is substantial compared to the TDD approach used with other back-end .Net development methodologies.

Debugging and Development: Similar to my testing argument; most mainstream browsers have great development and debugging plugins that make development far less frustrating and enjoyable today. However, these still do lack the richness in capability and ease of use when debugging domain/business objects on the back-end within Visual Studio.

Coupling: Domain/Business logic is tightly coupled to JavaScript runtimes. The browser in this case.

Code Security: This is one is pretty straightforward.

Cross-Browser Compatibility: While less of a problem today it does warrant some consideration.

Is there other high level items or constraints that I may be missing?

答:
I think many of your main points are quite misguided; claiming that "yes browsers can do it but Visual Studio is better" is not going to convince your coworkers (who probably are more used to debugging JS than to working with VS). Also:

number 3 is not an actual issue; you can write JS that does not rely in the browser version and that means no more restriction that you would have by writting it in C# (in fact it could be argued that you are restricting yourself more by using C#/CLR, since you can run JS on your server).

number 5 is also senseless; even historically, most cross browser issues have been related with the implementation of the DOM (how to access a form, input field, which properties those support, etc.) than with the JS itself. A well written JS should have no issues.

The main factor is that, as always, you cannot trust the client. Unless the result of the business logic is only output for that client use, you cannot implement it because you cannot be sure if that result comes from your logic, or from other piece of software claiming to be your logic.

Imagine that your bank worked like that; when you logged in it would send your browser the status of your accounts at your last login and the list of transactions that have happened, so that the browser calculates the current amount in your accounts and sends that data back to the bank (who would store it in their DB). Does that sound right? Maybe someone would try to profit from this architecture?

Even in a schema where people would not profit, like SETI@home1, some people "hacked" the legit program just to improve their statistics. If someone would benefit from feeding your system false business results, at some point someone will try. Moving the business logic to the browser just makes it insanely easy to do so.

Additionally, moving your logic to the customer will usually mean that your data will be harder to secure, since you will need to give access to almost everything to the browser so it can process the business logic. Getting the granularity that allows access to all that is needed but not a single bit more is going to be a lot of work.

1: In case you do not remember, SETI@Home was a program that you installed in your computer to process data from a radiotelescope in its spare time; in the hope of finding a signal send by an extraterrestial life form.


答:
I write this from the perspective of a long-time .NET developer being pulled inexorably into the client-side JavaScript world, so I assume that I probably share some of the same biases as you. I only bring this up because I think a lot of your bullet points are probably biased by your experience and relative comfort with C# and .NET over JavaScript.

For instance:

Testing: While we can leverage testing frameworks such as Jasmine the level of effort involved with developing and integrating these
  types of test scripts is substantial compared to the TDD approach used
  with other back-end .Net development methodologies.

That is being challenged daily by the JavaScript community. There is a significant amount of effort that goes into a proper .NET TDD approach that I think you're glossing over here. Certainly no more so than the ever improving JavaScript testing frameworks. But, as you are presumably more familiar with the .NET-related tooling and practices, it seems what you're really concerned with is the learning curve associated with adopting JavaScript-related new tooling and practices. That's a valid concern, but not really the same as ".NET is better".

Debugging and Development: Similar to my testing argument; most mainstream browsers have great development and debugging plugins that
  make development far less frustrating and enjoyable today. However,
  these still do lack the richness in capability and ease of use when
  debugging domain/business objects on the back-end within Visual
  Studio.

It's hard to argue against the rich debugging capabilities of Visual Studio, so I won't. :-)

But, I would argue that the vast majority of the time (in my experience) only a small subset of the debugging capabilities of VS are ever being used. Most of what happens in the debugger is stepping through the code from breakpoint to breakpoint, inspecting flow and state along the way. One could argue that this can be done just as well in (well designed) JavaScript code on the client as it can in C# code on the server. Especially when using VS as the debugger.

Coupling: Domain/Business logic is tightly coupled to JavaScript runtimes. The browser in this case.

I'm not sure I agree with this. Well modularized JavaScript code does not need to coupled to the browser. Business-logic code (as opposed to DOM-manipulating code) can and should be written such that it can be executed and tested without the browser.

Cross-Browser Compatibility: While less of a problem today it does warrant some consideration.

I agree. When writing code for .NET on the server, you know and control what runtime environment your code is running under. With JavaScript, there may be subtle differences with some code between the different JS engines. I wonder how much of a real impact this would make, though. Have you come across an actual example of this or is it hypothetical at this point?

Code Security: This is one is pretty straightforward.

This is the big one, for me. And the deal-breaker. It's simply the case that code running in the browser (and not on the server) is out of your control, unless you can control the browser, too. A responsible app would have to double-check all of the business-logic performed on the client, since the integrity of the client should not be trusted. This would seem to me to lead to either a lot of duplicate code, or an untrustworthy app. This is less of a concern with an internal-only corporate app than with a site open to the public, but it should still be a concern nonetheless.

All of this is to say that, if I were on your team, I would agree with you. :-) But not for the reasons you provided, which wouldn't be very convincing to someone eager to embrace JavaScript and client-side programming. And those arguments are getting weaker by the day.

Title: Client-Side JavaScript Business Logic in .Net Solution Stack

Body:
Fellow developers on other teams I interface with seemingly question my judgement calls as they pertain to the placement of coded business logic in a .Net MVC/Knockout web application currently under development. Granted, these types of questions have far reaching implications as they pertain to high-level architectural design patterns but warrant a detailed analysis nonetheless.

For example, let’s say we have a chunk of code that pulls data from a database, runs some calculation and then validates it against some user input. The argument consistently raised is such that the layers outside of the client browser (depicted below) should simply facilitate activities such as storing and passing data, security and other such activities that fall outside of implementing business logic. Then, within the browser, business rule validation and implementation.

[Client Browser/JS] <=> REST <=> [IIS/.Net MVC] <=> WCF/SQL <=> [WCF Endpoints & Databases]

Granted, there are numerous client-side JavaScript frameworks do promote this type of implementation pattern but I believe the intent with these assumes that the business rules and processes will always be executed client-side. Said another way; coupled to the browser.

In my particular circumstance I’ve come up with a few arguments against such an architecture and I want to make sure I’m not missing anything or being misleading.

Testing: While we can leverage testing frameworks such as Jasmine the level of effort involved with developing and integrating these types of test scripts is substantial compared to the TDD approach used with other back-end .Net development methodologies.

Debugging and Development: Similar to my testing argument; most mainstream browsers have great development and debugging plugins that make development far less frustrating and enjoyable today. However, these still do lack the richness in capability and ease of use when debugging domain/business objects on the back-end within Visual Studio.

Coupling: Domain/Business logic is tightly coupled to JavaScript runtimes. The browser in this case.

Code Security: This is one is pretty straightforward.

Cross-Browser Compatibility: While less of a problem today it does warrant some consideration.

Is there other high level items or constraints that I may be missing?


问:
Why would a program use a closure?
After reading many posts explaining closures here I'm still missing a key concept: Why write a closure?  What specific task would a programmer be performing that might be best served by a closure?

Examples of closures in Swift are accesses of an NSUrl and using the reverse geocoder. Here is one such example. Unfortunately, those courses just present the closure; they do not explain why the code solution is written as a closure.

An example of a real world programming problem that might trigger my brain to say, "aha, I should write a closure for this", would be more informative than a theoretical discussion.  There is no shortage of theoretical discussions available on this site.

答:
A closure is a shorthand way of writing a method where it is to be used.  It saves you the effort of declaring and writing a separate method.  It is useful when the method will be used only once and the method definition is short.  The benefits are reduced typing as there is no need to specify the name of the function, its return type or its access modifier.  Also, when reading the code you don't have to look elsewhere for the method's definition.

The above is a summary of Understand Lambda Expressions by Dan Avidar.

This clarified the use of closures for me because it clarifies the alternatives (closure vs. method) and the benefits of each.

The following code is used once, and once only during setup.  Writing it in place under viewDidLoad saves the trouble of searching for it elsewhere, and shortens the size of the code.

```<code>myPhoton!.getVariable("Temp", completion: { (result:AnyObject!, error:NSError!) -> Void in
  if let e = error {
    self.getTempLabel.text = "Failed reading temp"
  } else {
    if let res = result as? Float {
    self.getTempLabel.text = "Temperature is \(res) degrees"
    }
  }
})
</code>```

In addition, it provides for an asynchronous process to complete without blocking other parts of the program, and, a closure will retain a value for reuse in subsequent function calls.

Another closure; this one captures a value...

```<code>let animals = ["fish", "cat", "chicken", "dog"]
let sortedStrings = animals.sorted({ (one: String, two: String) -> Bool in return one > two
}) println(sortedStrings)
</code>```

Title: Why would a program use a closure?

Body:
A closure is a shorthand way of writing a method where it is to be used.  It saves you the effort of declaring and writing a separate method.  It is useful when the method will be used only once and the method definition is short.  The benefits are reduced typing as there is no need to specify the name of the function, its return type or its access modifier.  Also, when reading the code you don't have to look elsewhere for the method's definition.

The above is a summary of Understand Lambda Expressions by Dan Avidar.

This clarified the use of closures for me because it clarifies the alternatives (closure vs. method) and the benefits of each.

The following code is used once, and once only during setup.  Writing it in place under viewDidLoad saves the trouble of searching for it elsewhere, and shortens the size of the code.

myPhoton!.getVariable("Temp", completion: { (result:AnyObject!, error:NSError!) -> Void in
  if let e = error {
    self.getTempLabel.text = "Failed reading temp"
  } else {
    if let res = result as? Float {
    self.getTempLabel.text = "Temperature is \(res) degrees"
    }
  }
})

In addition, it provides for an asynchronous process to complete without blocking other parts of the program, and, a closure will retain a value for reuse in subsequent function calls.

Another closure; this one captures a value...

let animals = ["fish", "cat", "chicken", "dog"]
let sortedStrings = animals.sorted({ (one: String, two: String) -> Bool in return one > two
}) println(sortedStrings)


答:
While your programming should tend towards explicit  over implicit "as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live", you can assume a few basic things that your psycho successor will be competent in.

One of those is the syntax of the language he is using.

```<code>obj.NeedsChange = obj.Performance <= LOW_PERFORMANCE;
</code>```

is very clear to anyone who knows C/C++/C#/Java/Javascript syntax.

It's also much more readable than 8 lines.

```<code>if (obj.Performance <= LOW_PERFORMANCE)
{
    obj.NeedsChange = true;
}
else
{
    obj.NeedsChange = false;
}
</code>```

and less prone to mistakes

```<code>if (obj.Performance <= LOW_PERFORMANCE)
{
    obj.NeedsChange = true;
}
else
{
    obj.Needschange = false;
}
</code>```

And it's better than adding unnecessary characters, as if you half-forgot the syntax of the language:

```<code>obj.NeedsChange = obj.Performance <= LOW_PERFORMANCE ? true : false;

obj.NeedsChange = (obj.Performance <= LOW_PERFORMANCE);
</code>```

I think there is much wrong about the C-like syntax of many languages: inconsistent order of operations, inconsistent left/right associativity, overloaded uses of symbols, braces/indentation duplication, ternary operators, infix notation, etc.

But the solution isn't to invent your own proprietary version of it. That way lies madness, as everyone creates their own.

Generally the #1 thing that makes Real WorldTM code unreadable is the amount of it.

Between a non-pathological 200 line program and an trivially identical 1,600 line program, the shorter one will almost always be easier to parse and understand. I would welcome your change any day.

Title: Best practice boolean assignment

Body:
While your programming should tend towards explicit  over implicit "as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live", you can assume a few basic things that your psycho successor will be competent in.

One of those is the syntax of the language he is using.

obj.NeedsChange = obj.Performance <= LOW_PERFORMANCE;

is very clear to anyone who knows C/C++/C#/Java/Javascript syntax.

It's also much more readable than 8 lines.

if (obj.Performance <= LOW_PERFORMANCE)
{
    obj.NeedsChange = true;
}
else
{
    obj.NeedsChange = false;
}

and less prone to mistakes

if (obj.Performance <= LOW_PERFORMANCE)
{
    obj.NeedsChange = true;
}
else
{
    obj.Needschange = false;
}

And it's better than adding unnecessary characters, as if you half-forgot the syntax of the language:

obj.NeedsChange = obj.Performance <= LOW_PERFORMANCE ? true : false;

obj.NeedsChange = (obj.Performance <= LOW_PERFORMANCE);

I think there is much wrong about the C-like syntax of many languages: inconsistent order of operations, inconsistent left/right associativity, overloaded uses of symbols, braces/indentation duplication, ternary operators, infix notation, etc.

But the solution isn't to invent your own proprietary version of it. That way lies madness, as everyone creates their own.

Generally the #1 thing that makes Real WorldTM code unreadable is the amount of it.

Between a non-pathological 200 line program and an trivially identical 1,600 line program, the shorter one will almost always be easier to parse and understand. I would welcome your change any day.


问:
Which is more maintainable -- boolean assignment via if/else or boolean expression?
Which would be considered more maintainable?

```<code>if (a == b) c = true; else c = false;
</code>```

or

```<code> c = (a == b);
</code>```

I've tried looking in Code Complete, but can't find an answer.

I think the first is more readable (you can literally read it out loud), which I also think makes it more maintainable. The second one certainly makes more sense and reduces code, but I'm not sure it's as maintainable for C# developers (I'd expect to see this idiom more in, for example, Python).

答:
The second. It has less repetition (DRY) and is easier to understand what is going on, that c holds to value of whether or not a and be b are equal.

IMHO, even better would be

```<code>c = a == b
</code>```

Just as I would write

1 + 2 + 3 instead of ((1 + 2) + 3)

5 + 3 * 7 instead of (5 + (3 * 7))

Obviously and trivially unnecessary code is not a virtue. It's cluttered.

Body:
The second. It has less repetition (DRY) and is easier to understand what is going on, that c holds to value of whether or not a and be b are equal.

IMHO, even better would be

c = a == b

Just as I would write

1 + 2 + 3 instead of ((1 + 2) + 3)

5 + 3 * 7 instead of (5 + (3 * 7))

Obviously and trivially unnecessary code is not a virtue. It's cluttered.


问:
Does UTF-16 have some kind of separator in it?
From the UTF-16's wikipedia entry, the second sentence states it's a variable length encoding.

But where is the separator between a 16-bit character and 32-bit encoding? I know a lot of characters can be stored in the 16-bit character, so people can optimize UTF-6 that way, but I'm still curious because there could come a time when we could surpass the 16-bit mark.

And no worries, I know UTF-8 is standard. I'm just curious.

答:
It sounds like you're asking for the mechanism that allows UTF-16 to represent 32-bit characters, which is called surrogate pairs. That Wikipedia article pretty thoroughly explains it.

Incidentally, we surpassed 16 bits a long time ago. In fact, the main reason UTF-16 is widely used is that the fixed-length UCS-2 encoding became popular back when people thought 16 bits would be enough, then it wasn't, so UTF-16 is the easy-to-port-to option for everyone who started using UCS-2.


答:
Most of the developers will be able to understand the 2nd form with a glance. In my opinion over simplification as in 1st form is simply unnecessary.

You can improve the readability by adding spaces and braces such as:

```<code>obj.NeedsChange =    obj.Performance <= LOW_PERFORMANCE;
</code>```

or

```<code>obj.NeedsChange = ( obj.Performance <= LOW_PERFORMANCE );
</code>```

as mentioned by Jacob Raihle.

Title: Best practice boolean assignment

Body:
Most of the developers will be able to understand the 2nd form with a glance. In my opinion over simplification as in 1st form is simply unnecessary.

You can improve the readability by adding spaces and braces such as:

obj.NeedsChange =    obj.Performance <= LOW_PERFORMANCE;

or

obj.NeedsChange = ( obj.Performance <= LOW_PERFORMANCE );

as mentioned by Jacob Raihle.


问:
Confused in NoSql data model
I have a web application that uses MongoDB as primary database. This is the first project I do with a NoSQL DB. I'm trying to create the application model  but I'm confused. I know NoSQL databases are non-normalized and it is normal to replicate data avoiding joins (which are not supported) but I'm now thinking of this scenario:

I have the User class containing email address and the user can change it in the profile page. This email address is displayed in a few pages in different environments and I think the right choice is to embed this property in a few class documents (ex.: product subscription, invoice, shopping cart, ... ).

What if the user changes his email address? Do I have to trigger multiple updates to change every collection, every document that embeds this property?

答:
If i understand your question right...

For an example:

```<code>User Model:
    {
     name: String,
     email: String
     ...
     ...
    }
</code>```

other models (product subscription, invoice, shopping cart) will have ref. to User model, for example Invoice Model:

```<code>{
 name: String,
 amount: Number,
 date: Date
 ...
 ...
 _user: { type: ObjectID, ref: 'UserModel'}
}
</code>```

then when you fetching data for models that have user reference you can populate _user, and have current user object into data that you are fetching from db.

You don't need to store user data in every single model only _id with reference to User Model. With this implementation you only need to update your User collection.

Title: Confused in NoSql data model

Body:
If i understand your question right...

For an example:

User Model:
    {
     name: String,
     email: String
     ...
     ...
    }

other models (product subscription, invoice, shopping cart) will have ref. to User model, for example Invoice Model:

{
 name: String,
 amount: Number,
 date: Date
 ...
 ...
 _user: { type: ObjectID, ref: 'UserModel'}
}

then when you fetching data for models that have user reference you can populate _user, and have current user object into data that you are fetching from db.

You don't need to store user data in every single model only _id with reference to User Model. With this implementation you only need to update your User collection.


问:
Multithreading synchronization interview question: Find n words given m threads

Is there a way this problem could benefit from a solution with multiple threads, rather than a single thread?

In an interview, I was asked to solve a problem using multiple threads. It appears to me that the multiple threads lends no benefit.

Here's the problem:

You are given a paragraph , which contain n number of words, you are
  given m threads. What you need to do is , each thread should print one
  word and give the control to next thread, this way each thread will
  keep on printing one word , in case last thread come, it should invoke
  the first thread. Printing will repeat until all the words are printed
  in paragraph. Finally all threads should exit gracefully. What kind of
  synchronization will use?

I strongly feel we cannot take any advantage of threads here, but believe the interviewer is trying to measure my synchronization skills. Am I missing something in this problem that would make multiple threads have value?

No need of code, just put some thoughts. I will implement by myself.

答:
I'd say that this kind of question is very hard to answer, because it asks for the best way to do something completely stupid. My brain just doesn't work that way. It cannot find solutions for stupid questions. My brain would immediately say that under these conditions, using multiple threads is pointless, so I would use a single thread. </p>

<p>I'd then ask them to either give a real world question about threading, or to let me give a real world example of some serious threading. </p>

Body:
I'd say that this kind of question is very hard to answer, because it asks for the best way to do something completely stupid. My brain just doesn't work that way. It cannot find solutions for stupid questions. My brain would immediately say that under these conditions, using multiple threads is pointless, so I would use a single thread.

I'd then ask them to either give a real world question about threading, or to let me give a real world example of some serious threading.


答:
It's a very similar principle to UTF-8. In UTF-8, you can look at a single byte and it is either a "single byte code point", "first of two bytes", "first of three bytes", "first of four bytes" or "continuation of two, three or four byte code point". </p>

<p>In UTF-16, you can look at a single 16 bit value, and it is either a "single 16-bit word code point", or "first of two halves" or "second of two halves": The codes D800 to DBFF are "first halves", the codes DC00 to DCFF are "second halves", and to get a 32 bit code point you combine the last ten bits of each, giving a 20 bit value, and add 0x10000. </p>

Title: Does UTF-16 have some kind of separator in it?

Body:
From the UTF-16's wikipedia entry, the second sentence states it's a variable length encoding.

But where is the separator between a 16-bit character and 32-bit encoding? I know a lot of characters can be stored in the 16-bit character, so people can optimize UTF-6 that way, but I'm still curious because there could come a time when we could surpass the 16-bit mark.

And no worries, I know UTF-8 is standard. I'm just curious.

Body:
It's a very similar principle to UTF-8. In UTF-8, you can look at a single byte and it is either a "single byte code point", "first of two bytes", "first of three bytes", "first of four bytes" or "continuation of two, three or four byte code point".

In UTF-16, you can look at a single 16 bit value, and it is either a "single 16-bit word code point", or "first of two halves" or "second of two halves": The codes D800 to DBFF are "first halves", the codes DC00 to DCFF are "second halves", and to get a 32 bit code point you combine the last ten bits of each, giving a 20 bit value, and add 0x10000.


问:
Should Repositories return IQueryable?
I have been seeing a lot of projects that have repositories that return instances of IQueryable. This allows additional filters and sorting can be performed on the IQueryable by other code, which translates to different SQL being generated. I am curious where this pattern came from and whether it is a good idea.

My biggest concern is that an IQueryable is a promise to hit the database some time later, when it is enumerated. This means that an error would be thrown outside of the repository. This could mean an Entity Framework exception is thrown in a different layer of the application.

I have also run into issues with Multiple Active Result Sets (MARS) in the past (especially when using transactions) and this approach sounds like it would lead to this happening more often.

I have always called AsEnumerable or ToArray at the end of each of my LINQ expressions to make sure the database is hit before leaving the repository code.

I am wondering if returning IQueryable could be useful as a building block for a data layer. I have seen some pretty extravagant code with one repository calling another repository to build an even bigger IQueryable.

答: From a pure architecture standpoint, IQueryable is a leaky abstraction. As a generality, it provides the user with too much power. That being said, there are places where it makes sense. If you are using OData, IQueryable makes it extremely easy to provide an endpoint that is easily filterable, sortable, groupable... etc. I actually prefer to create DTO's that my entities map onto and the IQueryable returns the DTO instead. That way I pre-filter my data and really only use the IQueryable method to allow client customization of the results.</p>

Title: Should Repositories return IQueryable?


问:
How to find a programming mentor?
I decided to learn programming. I've been reading SO for few days, and I think I will start with C++, as I read some articles. I am aware of loops, arrays, program logic and objects a little and I need someone to look me over and help me with small questions I get when doing my first projects.

So here is the question - where do I find such guy? I don't got any friends who program and all.

EDIT: 2 years later, I am still looking for mentor. I did not actively code just started 3 months again. I work on Objective-C and iOS programming and game programming with Cocos2d. If you want to become my mentor, drop me a or comment.

答:
Joining an open-source project is certainly one way to get started. However, I've been using open-source software for years, and quite frankly, the quality on almost all such projects is generally in the toilet. If you learn your programming and design skills entirely from them, you'll probably pick up some very poor ones along with the good ones, with no way to tell the difference between them.

What do you want to learn programming for? The answer to that will determine what you should look for, and where. Here are some common answers, and my professional opinion on how to pursue them (keep in mind that it is just opinion, though IMHO, accurate):

Just to say that you know how to do it.

Then you don't really need a mentor, and C++ is a poor place to start. I love C++, it's my first choice for general programming, but play with another language instead. I'd suggest Python; it has a much gentler learning curve than C++, and unlike some languages (no names mentioned, I didn't wear my asbestos underwear today) you'll still learn a few useful skills in case you want to get into it further later. A lot of the concepts can translate directly to C++ if you decide to continue on that route.

Just to try it out and see if you like it.

An open-source project might be good enough for that. Pick a program that you like, but that you've found some problems or irritations with, and offer your help to whoever is running it. Most open-source projects are open to contributions, that's generally why they're open-source in the first place.

However, in that case, do not try C++ as your first programming language. It's not hard to master the basics, but C++ is low-level enough that you can get some serious and very hard-to-find bugs in your programs. Unless you already know you love programming, or you're as stubborn as the proverbial ox, or have already found a mentor who can point you in the right direction, that will kill any budding interest you might have in the field. See the above answer about Python, it's better suited for that.

Because you have an idea for a specific program you want to write.

(I don't think that the OP is in this category, I'm putting it in for later readers.)

Do you have any idea of the time required to master program design and implementation? As a hint, it's measured in years. You might be able to come up with a half-decent design after only a few months of study, if you're both smart and extremely lucky, but anyone with a little experience who has to work on it (including you, later) will wish that you'd never been born -- I speak from experience. :-) Unless the idea is so super-secret that no one else can know about it until it's done, don't bother. Hire an experienced programmer to do it for you, or if you can't afford one but still want the program badly enough, offer to partner with one -- you handle the business side and let him handle the programming part. Most good developers would prefer to be programming, so that kind of offer can be worth it to them.

Because you already know that you're fascinated by programming and want to learn more.

Then you're on exactly the right track. :-) Whether it's just as a hobby or is something you might turn into a career later, if you've got the kind of personality that finds it endlessly fascinating, the best thing you can do is to immerse yourself in it. C++ is as good a language as any, in that case, and a mentor will definitely help (and with more than just developing your skills; it can get lonely without friends who share your passion).

Title: How to find a programming mentor?


答:
I cannot be sure that each CSV file has only been processed once...

You might want to attempt to solve your question by handling this first. If I am getting this right, the crux of your problem doesn't appear to be individual duplicate transactions (since you mentioned "I know for sure that there are no duplicate records in each CSV file"), but to prevent duplicate processing per file.

Hence, you can consider adding some kind of state logic in your Java application that knows whether a file has been processed by computing and storing its checksum, e.g. its MD5 hash. Once you have a matching checksum, you know that there's a good chance the file has been processed before. You can perform further verification such as by inspecting the number of lines, or other certain unique identifiers of each file.

Further extending this idea, if there are possibilities of the same transaction appear across different CSV files, then your only other option, besides updating the database schema to handle duplicate records properly, is to store all the processed transactions locally within your Java application. If there can be multiple instances of your application (either on the same computer, or across a network), then you'll either need yet another centralized database to handle this, or some distributed data grid... by then, the better option is still back to the drawing board to improve on your existing database schema.

edit

To flip things around, the other considerations to look into <s>, if changing the database schema to handle duplicates nicely is entirely don't-even-think-about-it nigh impossible,</s> is to evaluate how much data your Java application will need to process at any given time, and how fast the connection is between the database and your application.

On the lower end, say your application is processing only 10 records per file, averaging one file an hour. The network connection is very good, say almost as good as accessing a locally-hosted database. In this case, I don't think there's much of a performance impact from having to query all the records.

On the extreme end, your application is expected to read thousand-line-long transaction files every 10 seconds, and the network connection is extremely bad, say taking a minute to query all the records. In this case, you have more concern about processing the files in a speedy manner, and this is how you can probably suggest modifying the database schema. :)

So, assuming all is fine in the lower-end case, what would be an efficient way of comparing a relatively large data set with a smaller input set for duplicates? I'll suggest marshalling the XML payload you get into a HashSet. Also, I hope you have a Transaction domain class that has properly-implemented hashCode() and equals() methods. A Java 8 potential solution would then be:

```<code>// assuming your database records are marshalled into currentSet
inputSet.stream().filter(v -> !currentSet.contains(v))
                    .forEach( /* these are the new records to send to the database */);
</code>```

Also, the elephant in the room: concurrent insertions. Will there be any? If so, how do you intend to handle it then?

Title: Java & REST API: How do I check for duplicate before inserting record?

Body:
I am developing an application in Java to parse and upload records from a CSV to an online database, via a REST API.

While I know for sure that there are no duplicate records in each CSV file, I cannot be sure that each CSV file has only been processed once (*see clarification below), so I need to check for duplicates before inserting.

[CLARIFICATION] I cannot implement a solution by checking that each CSV file has only been processed once. The CSV files contain bank transaction records downloaded from a bank. Therefore I know that each individual CSV file does not contain duplicates. However, multiple CSV files could be downloaded for the same date range, or for overlapping date ranges, etc. - so I need to check for duplicates at the transaction level rather than the file level.

Unfortunately I have no control over the back-end database, and I can only use the methods available via the API. This means the usual solutions using SQL (e.g. this question) are not suitable.

Methods available from API (http://help.moneytrackin.com/index.php/REST_API):

listTransactions

editTransaction

insertTransaction

Methods available but probably not relevant:

listProjects

listWriteProjects

getBalance

getTags

newProject

deleteProject

listTagTransactions

deleteTransaction

listCurrencies

userData

It is not a huge database: only four columns, and a few thousand records.

It seems like my only option is to iterate over each record to be inserted and compare it to each record from the database:

```<code>get ListOfRecordsInDb from database using listRecords(). Store in HashMap,
    local database or similar data structure??

for each record to be inserted,
    iterate over ListOfRecordsInDb, checking none of them match
       the record to be inserted
    if no match found, insert record
</code>```

This seems very inefficient. Are there any other options? If not, what is the most efficient way to compare thousands of records, using Java?

Answers to comments/questions:

What happens if you call insertTransaction with a transaction that
  already exists? Does it duplicate it or does it fail?

The transaction is successfully inserted as a duplicate

Does the CSV file have an "id" column?

No. The available columns are Date, Description, Amount and Balance. The combination of these makes each record unique, so I could potentially create an ID based on these.

Does listRecords() allow pagination, or can it only return all of the
  records?

It only returns the records, in XML format.

Body:
I cannot be sure that each CSV file has only been processed once...

You might want to attempt to solve your question by handling this first. If I am getting this right, the crux of your problem doesn't appear to be individual duplicate transactions (since you mentioned "I know for sure that there are no duplicate records in each CSV file"), but to prevent duplicate processing per file.

Hence, you can consider adding some kind of state logic in your Java application that knows whether a file has been processed by computing and storing its checksum, e.g. its MD5 hash. Once you have a matching checksum, you know that there's a good chance the file has been processed before. You can perform further verification such as by inspecting the number of lines, or other certain unique identifiers of each file.

Further extending this idea, if there are possibilities of the same transaction appear across different CSV files, then your only other option, besides updating the database schema to handle duplicate records properly, is to store all the processed transactions locally within your Java application. If there can be multiple instances of your application (either on the same computer, or across a network), then you'll either need yet another centralized database to handle this, or some distributed data grid... by then, the better option is still back to the drawing board to improve on your existing database schema.

edit

To flip things around, the other considerations to look into <s>, if changing the database schema to handle duplicates nicely is entirely don't-even-think-about-it nigh impossible,</s> is to evaluate how much data your Java application will need to process at any given time, and how fast the connection is between the database and your application.

On the lower end, say your application is processing only 10 records per file, averaging one file an hour. The network connection is very good, say almost as good as accessing a locally-hosted database. In this case, I don't think there's much of a performance impact from having to query all the records.

On the extreme end, your application is expected to read thousand-line-long transaction files every 10 seconds, and the network connection is extremely bad, say taking a minute to query all the records. In this case, you have more concern about processing the files in a speedy manner, and this is how you can probably suggest modifying the database schema. :)

So, assuming all is fine in the lower-end case, what would be an efficient way of comparing a relatively large data set with a smaller input set for duplicates? I'll suggest marshalling the XML payload you get into a HashSet. Also, I hope you have a Transaction domain class that has properly-implemented hashCode() and equals() methods. A Java 8 potential solution would then be:

// assuming your database records are marshalled into currentSet
inputSet.stream().filter(v -> !currentSet.contains(v))
                    .forEach( /* these are the new records to send to the database */);

Also, the elephant in the room: concurrent insertions. Will there be any? If so, how do you intend to handle it then?


答:
Get on the mailing list of a couple of reputable recruiters.  You're not "actively looking", but you're "keeping an eye out for interesting opportunities".  They will frequently include rate and salary information for positions in their e-mails.

Check job listing sites that quote rates or salaries.  Most listings don't publish the rates or salaries, but once in a while you'll find some.

You can also check out the Occupational Outlook Handbook published by the Dept of Labor.  Here is the page on Computer Software Engineers and Computer Programmers (see the Earnings section).  It lists average salaries, etc. but may not be specific to your geographic location, expertise, or industry.

Once you start seeing the rates for various types of positions then you'll start to see the variability that role, experience, location, and industry make in determining compensation.  From there you'll have to figure out what applies to you (and what to do next).

Hope that helps!

Title: How do you judge if you're paid enough?

Body: How do you evaluate how much you feel you ought to be paid as a junior programmer?</p>


问:
How widespread is the use of arabic numerals in Japanese and Chinese?
I'm localising a times-table app aimed at children. I understand that the Japanese and Chinese languages have a variety of ways to represent numbers. I also have read that, particularly with Japanese, 0-9 are commonly used for representing numbers.

Is it appropriate to use arabic numerals (particularly in education apps) is in Japanese and Chinese culture?

I know that arabic numerals aren't the solution to representing number. I also know that Japanese and Chinese cultures are completely different; however they are both very large markets with some similar challenges in localisation. I also know that large and small numbers (like 1,001 or 1.001) are formatted differently. This question is specific to integers less than 999 and greater than 0.

答:
In Japanese, Arabic numerals are widespread, and in computer contexts, are more common than the native character sets.  In Japan, things like tickets, receipts, etc. will nearly always use Arabic numerals.  As an example, Asahi Shimbun is one of the big Japanese newspapers.  Notice that despite having almost no latin-character character-set text, the date and time are rendered as "2015年6月18日12時31分" on the site.  You can assume any literate Japanese person will understand them perfectly.

I can't speak for Chinese.


问:
WebSite Design Knowledge Base Vs Blog
I'm currently developing a knowledge base for my company and we have already built a blog using a third party solution.

However, going through it, the functionality is a lot like the blog.  We have an inline wyiswyg editing experience on both.  Both systems store their data the same way.  Both systems have categories.  Both systems allow users to create new entries... etc..

Both systems support tagging, commenting, and searching...

So what I'm wondering is, what high level difference (functionality wise) is there between a blog and a knowledge base.

I feel like I could just reskin the knowledge base to be bloggy and call it a blog platform..

Are there any hard differences between what a knowledge base should be and a blog platform should be?  If I can isolate where they differ I think I can re-engineer the system to function as both under separate configurations.

答:
You might look on Wikipedia:

a blog ...

is a discussion or informational site published on the World Wide Web and consisting of discrete entries ("posts") typically displayed in reverse chronological order (the most recent post appears first).

a knowledge base (or KB) ...

is a technology used to store complex structured and unstructured information used by a computer system. The initial use of the term was in connection with expert systems

So I think the distinction is that a blog is a set of posts written by and for human beings, while a KB is structured, and supposed to somehow be processable and processed by software. Read also about knowledge-based systems,  inference engines (e.g. CLIPS ...) & business rules engines

However, for some technology providers, a KB is mostly a buzzword or a marketing term, and may just refer to some hypertext tool (with some limited indexing and searching abilities)

Title: WebSite Design Knowledge Base Vs Blog


答:
Go to some of the salary comparison websites e.g., glassdoor.com

search for your position, and use the filter to select your experience.

The range of salary stated on the website should be a rough guide.

Title: How do you judge if you're paid enough?


问:
How to scratch database that query faster for cloud computing
We are planning to develop a cloud based database driven web application which we would like world to use. Till date at the database side we have used fully normalized way to store the data and use multiple joins to retrieve the data and it is good if local system is concerned. But for web, we have learned that nowadays databases are not fully normalized so that there are least joins and loads faster. I have learned Magento is using flat tables to maintain faster loads and then using caching techniques to maintain the state of the data. Correct me if I am wrong.

We would like to adopt a kind of technique but not clear on balancing between normalization and denormalization.

Hope you guys have an answer, and tips to create fresh database which is faster load.

Please suggest.

Regards
Jay

答:
This sounds like a case of premature optimization to me. Your project is very, very tiny compared to a lot of applications running on a normalized database system. I know ambitions can get the best of you, but worry about global scaling if and when that becomes an issue.

Until then, I'd stick with normalized tables (3rd normal form is my go-to). Any RDBMS worth running can handle joins with ease--that's what it's built for. When you run into performance problems, don't denormalise until you find that to be the issue. Usually a good index or plan hint will help. There are, however, some perfectly good places to denormalise. Be careful, though, as this leads to data duplication, which is prone to error if you don't find every bit of data and keep it in sync.


问:
Error recovering emails in Delphi (POP3)
I'm new to programming with Delphi.

I have the latest version. I'm trying to display my emails using POP3 but I have a problem.

At one point I was wrong and did a loop with POP3.Retrieve() method instead of using POP3.RetrieveHeaders().

Delphi surely have downloaded all emails but when I try to start again, the CheckMessages() method is 0.

I tried using something like POP3.Free() or FreeAndNil(POP3) but nothing works for me, I can not check my mail.

What should I do now? When mail is downloaded to the POP3.Retrieve() method is no longer possible to see him again later?

Thanks in advance and sorry for my ignorance.

答:
A POP3 server only stores the new emails. Once an email has been retrieved, it is deleted from the server.

So, yes. Those emails that you downloaded accidentally are now completely gone and can't be retrieved again.


问:
How to setup build system for unit testing + mocking?
We have a legacy code base in entirely C++. Our build system is CMake. My first stab at unit testing was as follows:

Define a target (LibraryA). This library contains the code to test.

Define a unit test target per CPP test file in LibraryA being tested and link against LibraryA.lib.

Basically the source structure is like so:

```<code>LibraryA/
  Source/
    Utils/
      MyClass.cpp
      MyClass.hpp
      AnotherClass.cpp
      AnotherClass.hpp
    Network/
      Socket.cpp
      Socket.hpp
  Tests/
    Utils/
      TestMyClass.cpp
      TestAnotherClass.cpp
</code>```

What we have here is a mirror structure of the Source directory inside Tests. This structure allows me to use include order trickery at the compiler command line level to prioritize where class headers are found for mocking purposes. Each Test*.cpp file under Tests results in 1 executable. So 1 executable test per class being tested.

The issue is that I'm linking against LibraryA.lib in my test executable. This results in ODR violation because if I want to mock the Socket class, the LibraryA.lib will have already compiled symbols into it. Now I can't mock it without duplicating symbols and the linker will complain.

Overall setting up unit test structure has been a giant pain from the build system perspective when it comes to mocking.

Is there a good solution to this problem? Is my approach to test structure completely wrong?

答:
There are two options :

don't link Socket compiled binary into the libaryA, and compile libraryA with mocks. I think this is what you are trying to do : link time dependency injection.

use run-time dependency injection. Add interface for the Socket class, and use some kind of dependecy injection (factory, constructor or method), and in tests, instead of injecting the real Socket, inject the mock. This is even better, since you can test the calls to the mock.

The link time dependency injection (the first option), means that you inject the code during the linking time.

If Socket.h declares the Socker class, and Socket.cpp implements it, then add a header defining the mock class with the same name - Socket. It has to be in the same namespace as original Socket.

Then when you build the unit test, do not compile and link the Socket.cpp, you need to compile and link the mock class, and use it in the unit tests.


问:
Relation between Kernel & BIOS routines
How does a Kernel provides different functionality to OS? Does it use the BIOS routines or use special device drivers for this, or something else? If uses BIOS how does it come to know which routine performs what because different BIOS vendors have different coding? If not then what's the use for BIOS routines?</p>

答:
First, the BIOS (which is specific to PCs; most other computers, notably servers & tablets, have different firmware) is hardly used these days, except to boot the operating system kernel (and also for some weird things like ACPI & SMI), usually through some boot loader like GRUB (but both Windows and MacOSX have their own boot loaders).

32 bits (or 64 bits) operating system kernels like Linux don't really use the BIOS, but have their own drivers.

Please read also the wikipage about BIOS (and also UEFI) and about operating system.

I suggest to install, use, and study a free software OS like Linux; you'll be able to study all the relevant source code!

In the 1980s MS-DOS invoked BIOS services through INT 13H (which is probably still used by most boot loaders today).

See also osdev, it has lots of wikipages related to your question (and some examples of code).

Title: Relation between Kernel & BIOS routines


问:
PHP MVC how to access current user?
What is the best way to tell if a user is already logged in when accessing the page? I have seen many people talk about a Recognition service that will validate a user trying to login, but what about checking if they're already logged in? Assuming I'm storing the user's state in the session, how do I check for this? My application also requires a whitelist. On top of that, I need to redirect the user to a 403 page if they aren't in the whitelist, as opposed to the login page, or whatever page they requested if they are logged in.

My main roadblocks are:

Where to implement whitelist logic? Router, domain object?

Check if user is logged in? Controller?

How to get current user's role if they are logged in for my ACL? Do I call the Recognition service in my index.php and have my Recognition service return the user or their role and pass that along to the acl for the controller to use?

Note: I'm not really fond of the Controller Decorator because if the user can't access the method in the controller, how and where is that handled?

答: Most likely, your MVC already includes a variable accessible within the controller for accessing the user's information. If you store user roles in the database, you can restrict access to certain areas of the site in the router based on role, or on a page-by-page/controller class-by-controller class basis. Whitelisting should probably happen in the front controller, or the bootstrap file.</p>

Title: PHP MVC how to access current user?


问:
How do you judge if you're paid enough?
How do you evaluate how much you feel you ought to be paid as a junior programmer?</p>

答: Find out what you enjoy doing, find out what its pays, adjust your lifestyle to match. </p>

Title: How do you judge if you're paid enough?


问:
Should migrations modify data?
Imagine you have a table that has 5 columns, and you need to split this into two tables, because in your iterative process, your application has increased in complexity.

Should migrations change the data, as well? After all, you are dropping two columns and moving them to another table, and these two tables now probably need a foreign key to connect them, too.

What has me confused here is that as far as I know, migrations are only responsible for changing the structure of the database. It is all fine on a development database, but what would you do when you want to push this onto a live database?

答:
Migrations should change the data when needed - otherwise they don't fulfill their purpose of taking a database that works for an old version of the application and making it work for newer versions. Migrations are also the best place to do this, because you can make assumptions on the database's structure before and after the migration is run.

One thing to keep in mind though - if you plan to use the ORM for these changes, make sure you are using classes fit for the post-migration state of the database, not the ones the application is using, because the ones the application is using target the latests version of the database schema, not the one the migration will be running. If your ORM does not allow it don't use it in the migration - use raw SQL instead.

Title: Should migrations modify data?


问:
How to handle short notice (but high priority) maintenance tasks in SCRUM
currently shifting to SCRUM, we wonder what should be done exactly in the specific case :

Our analytics team need some script to be updated on the site we're managing. It occurs on a regular basis (possibly several times a month), but with no exact schedule, and they require  this to be done "ASAP". This somewhat "emergency" wouldn't allow us to use the normal process for devs which would imply to have it in the product backlog in order to put in in the sprint backlog during sprint planning meeting. But this is not an incident neither and from what I understood incidents are the only tasks that should enter the sprint backlog during the sprint (we have a contingency for that). Shortenning the sprints wouldn't be an option neither as they're already only 2 weeks long and for most of the tasks this is very appropriate. What are our options ?

Thanks !

EDIT : I need to mention SCRUM is not an alternative here (or actually is the only one we can use). We're in a big corporation deploying agile methodologies and enforcing SCRUM. DevOps Teams using scrum are just the end of a End-to-End delivery model based on SAFe, with a whole process before an item makes it to the product backlog (which is defacto less AGILE than what it should, but as simple employees we don't get to choose, "empowered" is more a good intention than reality...). In other words, if the answer implies switching methodology, we can't really apply it, especially as SCRUM fits well for most of our tasks, only a few don't quite find their place in this model...

答:
I've certainly experienced this in several agile settings.

I would suggest treating the 'rules' as guidelines which allow exceptions and changes from the normal process.

If these tickets are already well-sized, i.e. you know exactly what the work is AND you know their priority - apparently most important than I would allow these tickets to be paced directly into the ready column.

In order to complete tasks you will need to allow for this when sprint planning - either plan to have tasks that take up only 75% of the time available (not easy to do!) or allow for the fact that some tasks will not be completed when these 'asap' requests come in.

I'd also suggest that you look into using kanban which focused on a continuous flow of tickets and work rather than scrum which is focused on fixed length sprints.


答:
If you get more of those tasks, maybe KANBAN would be a better alternative, but you seem set for SCRUM, so lets see what you can do inside SCRUM:

SCRUM has a so-called impediment list. That's a list of all things that's keeping people from being productive. Such a task has not been planed in the sprint and doing it instead of working on the sprint goal is an impediment.

On the other hand, it seems that this indeed is a planned task. You could have a backlog item that says "handle requests from analytics" that you plan into every sprint.

Title: How to handle short notice (but high priority) maintenance tasks in SCRUM

Body:
currently shifting to SCRUM, we wonder what should be done exactly in the specific case :

Our analytics team need some script to be updated on the site we're managing. It occurs on a regular basis (possibly several times a month), but with no exact schedule, and they require  this to be done "ASAP". This somewhat "emergency" wouldn't allow us to use the normal process for devs which would imply to have it in the product backlog in order to put in in the sprint backlog during sprint planning meeting. But this is not an incident neither and from what I understood incidents are the only tasks that should enter the sprint backlog during the sprint (we have a contingency for that). Shortenning the sprints wouldn't be an option neither as they're already only 2 weeks long and for most of the tasks this is very appropriate. What are our options ?

Thanks !

EDIT : I need to mention SCRUM is not an alternative here (or actually is the only one we can use). We're in a big corporation deploying agile methodologies and enforcing SCRUM. DevOps Teams using scrum are just the end of a End-to-End delivery model based on SAFe, with a whole process before an item makes it to the product backlog (which is defacto less AGILE than what it should, but as simple employees we don't get to choose, "empowered" is more a good intention than reality...). In other words, if the answer implies switching methodology, we can't really apply it, especially as SCRUM fits well for most of our tasks, only a few don't quite find their place in this model...


答:
We have a development and support mode of operation. We follow SCRUM. We have a similar environment where we may not be able to predict what cases/tickets will come during a sprint, so we have allocated 80% of our time in a sprint for development work and 20% for the support work during sprint planning.

When we commit during a sprint, we have some stretch user stories that we might take in case when we do not have enough support work during that particular sprint and we are done with our committed user stories. I believe similarly you can also have a stretch user story for the script in the sprint backlog and take it if it comes else continue with your development work.

I hope this approach helps you.


问:
Generation of ids in offline/online application
I'm a bit confused about how to identify the elements in my application.

I have a rest backend with an sql database. I'm currently using numeric (autoincrement) ids as primary key and use these for foreign keys. I also defined uniques based on semantics.

My client is an app where I, for the most part, am mirroring the remote database. The goal of this is both to have a cache (performance) and to make possible to use the app offline. The offline usage can be temporary or permanent (user can use the app without ever connecting to the server).

So far I have been implementing the client with online usage in mind. So when the user creates a new item I would send a POST to the server, the server creates the item and gives it an id, and sends me back the item with the id, and I store it in the local database. This way I will use this id as foreign key also in the client database.

But the offline usage doesn't work like this. When I add an item without server I'll have to give it an id in the client. So this is immediately available to be updated, used in a foreign key, etc. Furthermore when offline is just temporary, that is the user connects later to the server, I have to synchronize the items which were added offline. If I'm using client-side ids, I would have to reemplace these in the server with server-generated ids, otherwise the database would look inconsistent and it may (though highly improvable) happen a clash. Or just use always clientside ids?

So my question is, how is this handled normally? I can think of 4 approaches:

Drop the ids entirely and use only uniques. I can get even updates working with this. For example a unique can be a name. But this can lead to issue as follows - if user was online and created an item. Goes offline and updates the name of the item, which is the unique, 2 times. I would have to store in the client the last value of the unique when a synchronisation happened in order to do the update in the server. And cascade update. Besides of this unique also occupies more space than numeric id in the database.

Drop the ids only in the client. So in the client I use only uniques (name, etc) and I send the server old-new value for updates, which is the same as in 1. The server uses ids internally but never sends this to the client.

Use the server ids and do a sync call as soon as the client goes online where the client-generated ids are replaced with server-generated.

Generate the ids always in the client - similar to described here maybe. (to garantee uniqueness among users e.g. device UUID + timestamp, but this leads to relatively long ids, not sure about space/performance implications here). And use them in the server instead of autoincr id. Or maybe use both?

答:
There is no way you can get around having more than one way of uniquely identifying your entities. The best you can do is grit your teeth and confine the problem to the smallest possible scope.

For instance:

assign the real IDs on the server only. The server should never even be aware that the client uses another ID scheme, only that it delivers new records that must receive a new real ID.

use a distinct ID scheme in the client that has no overlap with the real IDs (e.g. negative rather than positive values...)

change all places in the client that deal with entity finding so that they understand both schemes, and use the other if the one isn't assigned yet

change the one place in the app that posts new data to the server so that it updates the "real ID" after the save has been confirmed.

It doesn't really get simpler than that. (Of course, minimizing the places that have to be changed so that this solution becomes easier is a good idea anyway, per the principle of Don't Repeat Yourself.)