问:
self referencing tables, good or bad?
Representing geographical locations within an application, the design of the underlying data model suggests two clear options (or maybe more?).

One table with a self referencing parent_id column
uk - london (london parent id = UK id)

or two tables, with a one to many relationship using a foreign key.

My preference is for one self-refercing table as it easily allows to extend into as many sub regions as required.

IN general do people veer away from self referencing tables, or are they A-OK ?

答:
Necromancing.

The correct answer is: it depends on which database engine and on which management tool.

Let's make an example:

We have a report table,

and a report can have a parent (menupoint, like category),

and that parent can itselfs have a parent (e.g. Profit center),

and so on ad infinitum.

The most simple example of a standard recursive relationship, as with any self-referencing entity / hierarchy.

The resulting SQL-Server table is:

```<code>IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'dbo.FK_T_FMS_Reports_T_FMS_Reports') AND parent_object_id = OBJECT_ID(N'dbo.T_FMS_Reports'))
ALTER TABLE dbo.T_FMS_Reports DROP CONSTRAINT FK_T_FMS_Reports_T_FMS_Reports
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.T_FMS_Reports') AND type in (N'U'))
DROP TABLE dbo.T_FMS_Reports
GO

CREATE TABLE dbo.T_FMS_Reports
(
     RE_UID uniqueidentifier NOT NULL
    ,RE_RE_UID uniqueidentifier NULL
    ,RE_Text nvarchar(255) NULL
    ,RE_Link nvarchar(400) NULL
    ,RE_Sort int NOT NULL
    ,RE_Status int NOT NULL
    ,PRIMARY KEY CLUSTERED ( RE_UID )
);

GO

ALTER TABLE dbo.T_FMS_Reports  WITH CHECK ADD  CONSTRAINT FK_T_FMS_Reports_T_FMS_Reports FOREIGN KEY(RE_RE_UID)
REFERENCES dbo.T_FMS_Reports (RE_UID)
-- ON DELETE CASCADE -- here, MS-SQL has a problem
GO

ALTER TABLE dbo.T_FMS_Reports CHECK CONSTRAINT FK_T_FMS_Reports_T_FMS_Reports
GO
</code>```

But you get a problem:

When you need to delete a menupoint with all its submenupoints, you CANNOT set delete-cascade, because Microsoft SQL-Server doesn't support recursive cascaded deletes (on the other hand, PostGreSQL does [but only if the graph is not cyclic], while MySQL doesn't like this kind of table structure at all, because it doesn't support recursive CTEs).

So you kinda blow up deletion-integrity/functionality with it, making it mandatory to implement such functionality in your own code, or in a stored procedure (if your RDBMS supports stored-procedures).

This will no doubt blow up any kind of fully-automatic dynamic data import/export, because you can neither simply run a delete statement for all tables according to (non-self referencing) foreign-key relationships, nor can you do a simple select * and create an insert for every row in an arbitrary order.

For example, when you create an INSERT script using SSMS, then SSMS won't get the foreign key, and thus does indeed create insert-statements that will insert entrys with dependencies, before it inserts the dependency's parent, which will fail with an error, because the foreign-key is in place.

However, on proper database management systems (like PostgreSQL), with proper tooling, this shouldn't be a problem. Just undestand that just because you pay a lot for your RDBMS (I'm looking at you, Microsoft; Oracle = ?), and/or its tool-belt, it doesn't mean it is programmed properly. And neither does OpenSource (e.g. MySQL) make you immune to such wonderful minutiae.

The devil is in the details, as the old saying goes.

Now, not that you couldn't work-around such problems, but I really wouldn't recommend it, if your system is gonna be complex (e.g. 200+ tables).

Plus, in a usual commercial setting (as portrayed by Dilbert), you just won't be given that time.

A much better approach, though more difficult, would be a closure table.

That would have the added bonus that it also works on MySQL.

Once you implement the closure-functionality once, you'll have it working in additional places in almost no time at all.

Title: self referencing tables, good or bad?

Body:
Necromancing.

The correct answer is: it depends on which database engine and on which management tool.

Let's make an example:

We have a report table,

and a report can have a parent (menupoint, like category),

and that parent can itselfs have a parent (e.g. Profit center),

and so on ad infinitum.

The most simple example of a standard recursive relationship, as with any self-referencing entity / hierarchy.

The resulting SQL-Server table is:

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'dbo.FK_T_FMS_Reports_T_FMS_Reports') AND parent_object_id = OBJECT_ID(N'dbo.T_FMS_Reports'))
ALTER TABLE dbo.T_FMS_Reports DROP CONSTRAINT FK_T_FMS_Reports_T_FMS_Reports
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.T_FMS_Reports') AND type in (N'U'))
DROP TABLE dbo.T_FMS_Reports
GO

CREATE TABLE dbo.T_FMS_Reports
(
     RE_UID uniqueidentifier NOT NULL
    ,RE_RE_UID uniqueidentifier NULL
    ,RE_Text nvarchar(255) NULL
    ,RE_Link nvarchar(400) NULL
    ,RE_Sort int NOT NULL
    ,RE_Status int NOT NULL
    ,PRIMARY KEY CLUSTERED ( RE_UID )
);

GO

ALTER TABLE dbo.T_FMS_Reports  WITH CHECK ADD  CONSTRAINT FK_T_FMS_Reports_T_FMS_Reports FOREIGN KEY(RE_RE_UID)
REFERENCES dbo.T_FMS_Reports (RE_UID)
-- ON DELETE CASCADE -- here, MS-SQL has a problem
GO

ALTER TABLE dbo.T_FMS_Reports CHECK CONSTRAINT FK_T_FMS_Reports_T_FMS_Reports
GO

But you get a problem:

When you need to delete a menupoint with all its submenupoints, you CANNOT set delete-cascade, because Microsoft SQL-Server doesn't support recursive cascaded deletes (on the other hand, PostGreSQL does [but only if the graph is not cyclic], while MySQL doesn't like this kind of table structure at all, because it doesn't support recursive CTEs).

So you kinda blow up deletion-integrity/functionality with it, making it mandatory to implement such functionality in your own code, or in a stored procedure (if your RDBMS supports stored-procedures).

This will no doubt blow up any kind of fully-automatic dynamic data import/export, because you can neither simply run a delete statement for all tables according to (non-self referencing) foreign-key relationships, nor can you do a simple select * and create an insert for every row in an arbitrary order.

For example, when you create an INSERT script using SSMS, then SSMS won't get the foreign key, and thus does indeed create insert-statements that will insert entrys with dependencies, before it inserts the dependency's parent, which will fail with an error, because the foreign-key is in place.

However, on proper database management systems (like PostgreSQL), with proper tooling, this shouldn't be a problem. Just undestand that just because you pay a lot for your RDBMS (I'm looking at you, Microsoft; Oracle = ?), and/or its tool-belt, it doesn't mean it is programmed properly. And neither does OpenSource (e.g. MySQL) make you immune to such wonderful minutiae.

The devil is in the details, as the old saying goes.

Now, not that you couldn't work-around such problems, but I really wouldn't recommend it, if your system is gonna be complex (e.g. 200+ tables).

Plus, in a usual commercial setting (as portrayed by Dilbert), you just won't be given that time.

A much better approach, though more difficult, would be a closure table.

That would have the added bonus that it also works on MySQL.

Once you implement the closure-functionality once, you'll have it working in additional places in almost no time at all.


问:
Singleton or instantiate everytime I use?
I use a class that just extracts data from one known object, and distributes it to other known objects. No persistent configuration or such is needed in that class instance.

How should I decide whether to set up that class as a singleton, or just instantiate it every time I need it?

答: If the class has no state, you could consider turning it into a function or static method depending on your language.</p>

ContentLicense: CC BY-SA 3.0


答:
How do you determine what these 'known objects' are - if its hard-coded in code (ie the object is a static or singleton itself) then you might as well use a static method to perform the processing, just call that as needed.

I can't see why you'd need a whole class for this process, unless those known objects are considered state internally to the class. In this case, it depends how often you need it and the cost of constructing it, it it takes a lot of effort, a singleton is probably best.

Title: Singleton or instantiate everytime I use?

Body:
I use a class that just extracts data from one known object, and distributes it to other known objects. No persistent configuration or such is needed in that class instance.

How should I decide whether to set up that class as a singleton, or just instantiate it every time I need it?


问:
Where are octals useful?
I just banged my head against the table for some 20 minutes looking at a totally weird bug in PHP, and then I realized there's octal. The <%(*&#> octal.

In short, I padded some literals with zeros so the code would be aligned, I know, big mistake. Forgot about octals.

The question is, does anyone use octals for anything other than file permissions? (I personally prefer chmod ugo+rwx but I understand that if they have to be programmaticaly generated, it's useful to use octals.) But are they useful in any other situation?

答: A bit of an aside, but a public use is on the London Underground. Each train has both a physical identity, and a separate identity in the schedules which is displayed when in service - see here: https://upload.wikimedia.org/wikipedia/commons/4/49/LUL-S-Stock-at-Watford.jpg (note the 402 at the top of the destination display). Although the electronics for the displays are bog standard decimal-based, you never see digits 8 or 9 because they are tied to legacy octal-based hardware in the signalling system.</p>

Title: Where are octals useful?


答:
It is sometimes considered that the singleton is an anti-pattern. Unless the problem being solved specifically requires the use of the singleton pattern, it is generally best to avoid it.

You mention that the function would have no state or other long lived requirements, so the immediate need for an object is not there either.

A free function would be best (or static function or similar given the language and target), since it carries no state and doesn't introduce any issue associated with the singleton.

If a free function is not an option, an empty object (no data members) would probably be a close enough second option.

In general, my advice when choosing a pattern is to first understand what problem the pattern seeks to solve and what the limitations and constraints of the pattern would be. Once understood, if the problem being solved falls into that pattern's problem space then that pattern would be a candidate for use.


问:
Best x86 processor(computer) to learn computer architecture and assembly
I'm planning to build a computer as a hobby from scratch, with the least basic hardware possible in functionality so I can learn the basics of computer architecture and assembly language.

I already have a high end PC but exploring it I find it complicated to learn basic foundational comp architecture stuff.

I wanted to build a 286 processor computer, but found out 386 was the first 32 bit pc, but researching further I realized 486 would be a better option as its pipelining is what we have even now.

So I'm looking to build something very minimilistic with the lowest memory, processor and harddrive. Something like raspberry pi but with an x86 architecture, to do low level assembly and c programming and probably linux shell.

答:
If you want to learn assembly x86 isn't the best one to start with. Its probably better to use one of the ARM processors as you can find boards with these quite readily. x86 boards are not so common. Once you've learned assembly, you may learn the differences for x86, or more likely skip assembly altogether and go straight to a higher level language such as C.

The BBC has a board called the Micro Bit which is designed to teaching the very low level aspects of hardware and computing. Alternatives include the Arduino or, obviously, the RaspberryPi which does have a lot of educational materials prepared for it already.


问:
Proper propagation / handling of exceptions
I am trying to learn trough example on a proper way to handle exceptions. When should I catch it, when and how should I throw it further down the line ?

In this example I have a very simple setup:

MainMethod

ExceptionHandler // Here is where I'd like to catch and resolve most exceptions

ExceptionGenerator // Errors start from here

```<code>public List<String> readFile(String pathStr) throws InvalidPathException, IOException {

    Path path = Paths.get(Repository.fixPath(pathStr));         // This can throw both FileNotFoundException and InvalidPathException, I think. It should!
    List<String> fileContent;

    try {

        fileContent = Files.readAllLines(path, StandardCharsets.UTF_8);
        return fileContent;

    } catch (IOException e) {
        throw new IOException("Could not read file content");
    }
}

// FileNotFoundException (FNFE) should be sent to the previous method
private static String fixPath(String path) throws FileNotFoundException {

    if (path.isEmpty() || path == null)
        throw new FileNotFoundException();

    ...

    return path;
}
</code>```

Points of interest:

Should my readFiles method catch the FileNotFoundException thrown by the second method ? Should I then throw it again, like with the IOException ? How does the message exactly work (the parameter for the exception)? Is it actually usable in any way except printing it out ?

If I have IOException (it supersedes the FNFE, can I still throw the FNFE then just catch FNFE first, and IOE second?)

答:
```<code>catch (IOException e) {
    throw new IOException("Could not read file content");
}
</code>```

This is a very bad practise because you are losing all the stacktrace of e ! Therefore when catching this exception you won't have any information of the root cause of the exception.

If you really need to add a specific message at this layer, consider doing it like this: throw new IOException("Could not read file content", e);

What readFile must throw ? It depends on the verbosity you want to expose.

Verbose case

```<code>public List<String> readFile(String pathStr) throws FileNotFoundException, IOException { }
</code>```

This case is appropriate when you want to indicate to the caller that the exceptions throwed by this method should be handled differently.

Less verbose case

```<code>public List<String> readFile(String pathStr) throws IOException { }
</code>```

This case is appropriate when you don't want to bother with the details of the exception (just knowing "something went wrong" is enough).

Body:
catch (IOException e) {
    throw new IOException("Could not read file content");
}

This is a very bad practise because you are losing all the stacktrace of e ! Therefore when catching this exception you won't have any information of the root cause of the exception.

If you really need to add a specific message at this layer, consider doing it like this: throw new IOException("Could not read file content", e);

What readFile must throw ? It depends on the verbosity you want to expose.

Verbose case

public List<String> readFile(String pathStr) throws FileNotFoundException, IOException { }

This case is appropriate when you want to indicate to the caller that the exceptions throwed by this method should be handled differently.

Less verbose case

public List<String> readFile(String pathStr) throws IOException { }

This case is appropriate when you don't want to bother with the details of the exception (just knowing "something went wrong" is enough).


答:
If you'd really like to learn, why not build your own from nand gates? I highly recommend 'From nand to Tetris' a free 6 week course offered at Coursera at Coursera - Free public courses.

With this course, you build a 16 bit working computer, learn HDL, circuit design, build an assembler, operating system, and compiler.

Granted it's not x86, but certainly a great place to learn the basics. It will make learning the x86 so much easier.

Title: Best x86 processor(computer) to learn computer architecture and assembly

Body:
I'm planning to build a computer as a hobby from scratch, with the least basic hardware possible in functionality so I can learn the basics of computer architecture and assembly language.

I already have a high end PC but exploring it I find it complicated to learn basic foundational comp architecture stuff.

I wanted to build a 286 processor computer, but found out 386 was the first 32 bit pc, but researching further I realized 486 would be a better option as its pipelining is what we have even now.

So I'm looking to build something very minimilistic with the lowest memory, processor and harddrive. Something like raspberry pi but with an x86 architecture, to do low level assembly and c programming and probably linux shell.


问:
Which sorting algorithms have a different worst case complexity than their average case?
I'v been working on sorting for a while now but I can't figure these two questions apart,  I'm kind of getting mixed up somewhere ... Somebody help

a) Which sorting algorithms have a different worst case complexity than their average case?

b) Which sorting algorithms have a different best case complexity than their average case?

答:
Bubble Sort, O(N) in the best case, O(N ** 2) in the average and worst cases.

To get the O(N) behaviour, set a swapped boolean to false at the beginning of each pass, set it to true whenever you swap two elements. If you have swapped elements, you need to do another pass. This also works as a general termination criterion, as long as comparisons are deterministic, which means you can skip an O(N) counting pass before starting.


问:
Universal Standards for Data Interchange - Do they exist and do you follow them?
Mostly fact and maybe a little bit of opinion:

One of my pet peeves in programming is data interchange. I work exclusively with small business software (as opposed to working with corporate ERP systems) and I see that many small businesses store contacts two or three times in different types of software where there is little or no interchange. Time clock systems usually don't integrate with calendaring and project management systems. Task management may be in a system separate from project management, or more commonly, tasks are managed on paper or mentally. These are just a few examples of the data interchange problems I see every day in almost every small business.

It seems every software company has a different idea about how to store it's data and whether or not to expose that data for interchange and integration. If they do expose some of their data there is really no common standard to facilitate interchange or synchronization. You're always forced to read through the SDK/API documentation if you do want to program some type of integration and then it's almost never a painless experience to get it working and keep it working.

It would be really nice to receive an "electronic document" from our vendors that would allow us to quickly enter bills into our accounting system. It would be really nice if we hire a new employee that we could make one single entry somewhere, enter his roles and then he would be entered into all the correct systems even if his information would need to be flagged for review in systems such as accounting. It would be so nice if all our contacts were seamlessly shared between systems so that updating an address or phone number in one of them would make the changes in all of them.

Questions:

Do data interchange standards for common entities such as people, purchase orders, sales orders/invoices, shipping documents, projects, tasks, appointments, etc. already exist?

Assuming some do exist, are they commonly accepted, ratified standards?

Would you program a business system to use or follow these standards if the initial requirements of the project did not call for it? In other words, how common or accepted are these standards, enough to be followed every time?

答:
One that I have used is here: https://schema.org/docs/full.html. They have definitions for lots of things, from recipes, to various types of businesses.

It is used in many places too. For instance, Amazon orders etc contain Schema from here in their emails, and when you open up their email in Gmail or Inbox, you see a summary of what you ordered, the price, and others.


问:
Call methods of subclass when iterating over base type collection
Imagine this code:

```<code>using System;

public enum BaseClassType
{
    DerivedA,
    DerivedB
}

public abstract class BaseClass
{
    public BaseClassType Type;

    public BaseClass(BaseClassType type)
    {
        Type = type;
    }

    public virtual void Interact()
    {
        Console.WriteLine("BaseClass.Interact()");
    }
}

public class DerivedA : BaseClass
{
    public DerivedA() : base(BaseClassType.DerivedA) {}

    public void SomeMethodA(int signature0, float signature1)
    {
        Console.WriteLine("DerivedA.SomeMethodA");
    }
}

public class DerivedB : BaseClass
{
    public DerivedB() : base(BaseClassType.DerivedB) {}

    public void SomeMethodB(float signature0)
    {
        Console.WriteLine("DerivedB.SomeMethodB");
    }
}

public class Test
{
    public static void Main()
    {
        BaseClass[] elements = new BaseClass[] { new DerivedA(), new DerivedB() };
        foreach (var element in elements)
        {
            switch (element.Type)
            {
                case BaseClassType.DerivedA:
                    (element as DerivedA).SomeMethodA(5, 5f);
                    break;
                case BaseClassType.DerivedB:
                    (element as DerivedB).SomeMethodB(3f);
                    break;
            }
        }
    }
}
</code>```

I wonder what is the best OOP way to get rid off this type of switch? Maybe some pattern? The methods of the subclasses have completely different signatures, so I cannot extract it and make virtual in the base class.

答:
If your subclasses have methods with different types and values as parameters, then those aren't the same methods. They should be encapsulated behind a common, inherited method that knows what is appropriate to the concrete class. </p>

<p>If it isn't possible to for the subclass to get at these values, then your class hierarchy is flawed: the subclass is supposed to express a specialization of a some type that differs in some specifics, but it doesn't know these specifics! This is not something a design pattern can fix - you have to redraw the class boundaries in your system to make the types fit your business domain </p>

Body:
If your subclasses have methods with different types and values as parameters, then those aren't the same methods. They should be encapsulated behind a common, inherited method that knows what is appropriate to the concrete class.

If it isn't possible to for the subclass to get at these values, then your class hierarchy is flawed: the subclass is supposed to express a specialization of a some type that differs in some specifics, but it doesn't know these specifics! This is not something a design pattern can fix - you have to redraw the class boundaries in your system to make the types fit your business domain


问:
Can edit distance be used in a simple fashion to restrict editing to spelling mistakes only?
For a small hobby project I thought about giving users the ability to edit their submissions, but, since their submissions will be voted on by other users, restrict editing to correct (minor) spelling mistakes only, preferably natural-language-agnostic.

During a tentative investigation into the subject I thought I might utilize edit distance and related subjects such as (Damerau–)Levenshtein distance, for this.

So far I pondered about putting a certain edit distance threshold on either the entire original submission or on their individual words (for languages where this makes sense). Now, I certainly don't want to create a complex natural language processing algorithm, but I have a feeling this is a way too naive approach, particularly in light of languages such as Japanese and Chinese, etc, where replacing a single symbol could change the entire meaning of a sentence.

So, before delving deeper into these edit distance subjects, I thought I'd ask the community whether it is even feasible to merely use edit distance, in a fairly simple fashion like described above as a reasonably reliable measure for something like this. Is it? Or is this too naive and am I almost certainly bound to creating a complex natural language processing algorithm and/or use entire dictionaries for any reasonably reliable approach (in which case I'll probably ditch the entire idea altogether ;-))?

Come to think of it: since I can't remember ever coming across this kind of functionality on major sites with voting systems, I can probably guess the answer myself already, but I thought I'd ask you anyway, just to be sure.

答:
If you only want to edit spelling changes, then you'll be doing this on a word-by-word basis, so checking levenstein against the entire text is probably not going to work (especially as IIRC a small change up front can have a big knock-on effect in a large document).

Its possibly better to encode every word with a soundex (or better, a double-metaphone) code and allow changes there - but only if the code doesn't change (ie the word may change but the sound of it doesn't, so you can be reasonably sure its not been changed from its original meaning, just the spelling).

The ASpell (spell checker) project uses metaphone to offer replacement suggestions, so its very better suited for spelling alterations only.


问:
Design pattern how to deal with objects validation?
I am thinking if is there some design pattern to work with objects and its states. In my REST API I have a access token objects, these objects contain information about authenticated clients:

```<code>public class AccessToken {

    private final String accessToken;
    private DateTime expiration;
    private DateTime created;

}
</code>```

but this AccessToken has an expiration time. When I check, whether client is logged in (= token exists), I would like to check whether token is not expired.

Question

Should be this method - e.g. .isValid(), .isExpired() for better clarity and simplicity be in AccessToken class or should I have another class that will do a validation?

答:
I think it's the responsibility of the AccessToken to provide if it's expired or not.
Naming your method isExpired seems less ambiguous to me.

```<code>public class AccessToken {

    private final String accessToken;
    private DateTime expiration;
    private DateTime created;

    public final boolean isExpired() {
        return now > expiration;
    }

}
</code>```

Body:
I think it's the responsibility of the AccessToken to provide if it's expired or not.
Naming your method isExpired seems less ambiguous to me.

public class AccessToken {

    private final String accessToken;
    private DateTime expiration;
    private DateTime created;

    public final boolean isExpired() {
        return now > expiration;
    }

}


答:
I'm not sure if there is a named pattern (or not) for this technique - but either way I would not do it.

The DTO (data transfer object) is there to transfer the data over the wire, the business or application logic is tied to the REST API.

From Wikipedia;

... a DTO does not have any behavior except for storage and retrieval of its own data (accessors and mutators). DTOs are simple objects that should not contain any business logic that would require testing.

If you wish to provide the client with a utility class/method to check first if the token is still valid prior to making the REST call, I would provide the client with such a class outside of the DTO;

```<code>class AccessTokenValidation {
  public bool isValid(AccessToken token) {
    // client side logic as required
    return now > token.expiration;
  }
}
</code>```

Title: Design pattern how to deal with objects validation?

Body:
I am thinking if is there some design pattern to work with objects and its states. In my REST API I have a access token objects, these objects contain information about authenticated clients:

```<code>public class AccessToken {

    private final String accessToken;
    private DateTime expiration;
    private DateTime created;

}
</code>```

but this AccessToken has an expiration time. When I check, whether client is logged in (= token exists), I would like to check whether token is not expired.

Question

Should be this method - e.g. .isValid(), .isExpired() for better clarity and simplicity be in AccessToken class or should I have another class that will do a validation?

Body:
I'm not sure if there is a named pattern (or not) for this technique - but either way I would not do it.

The DTO (data transfer object) is there to transfer the data over the wire, the business or application logic is tied to the REST API.

From Wikipedia;

... a DTO does not have any behavior except for storage and retrieval of its own data (accessors and mutators). DTOs are simple objects that should not contain any business logic that would require testing.

If you wish to provide the client with a utility class/method to check first if the token is still valid prior to making the REST call, I would provide the client with such a class outside of the DTO;

class AccessTokenValidation {
  public bool isValid(AccessToken token) {
    // client side logic as required
    return now > token.expiration;
  }
}


问:
Is a memory of all possible permutations of a kilobyte block and pointers possible?
This is a hard enough idea to wrap my head around and I would greatly appreciate any edits/help to get it more readable for those in-the-know.

Is it theoretically possible to have a hard drive that has saved on it one copy of every possible binary permutation of one kilobyte and then have the rest of the system simply create pointers to these locations?

Would a system made such a way be any faster than simply having information stored directly?

To explain another way, say instead of having sentences:

"Hello, I'm Bob." and "That sandwich looks delicious."

...stored on the hard drive, we would have all permutations of the alphabet and other characters up to some number (say, 1000 characters or so), and then have store our sentences as something like:

[Pointer#21381723]

答:
There are two problems with that.

First, "all possible binary permutations of one kilobyte" is a huge amount of data.  1024 bytes * 8 bits per byte = 8192 bits in a kilobyte.  All possible permutations would be 2^8192.  That's around 1.09e+2466 kilobytes!  (For purposes of comparison, a 1 TB drive is 1e09 kilobytes.)

Second, even if you did have such an enormous table, and you indexed into it with pointers, what would you do if you wanted to reference some data smaller than exactly 1 KB?


答:
There are 28192 possible different 1K blocks. Storing them all would take 28202 bits of storage. Since the universe contains only about 1080 (or ~2266) particles, it's a safe bet that it isn't possible to store them all, and you don't have to wonder about whether it would save time or not.

But there is, in fact a more interesting way of answering this. You are suggesting creating an index into a huge pool of constants. But how would you know which index to dereference? Imagine for the sake of an argument that you want to store only 1-character blocks: a, b, c... Presumably your indices would be 0, 1, 2 etc., since that's the most efficient layout of storing those blocks.

Do you notice something about the arrangement? Your index is, in fact, a coded representation of the stored data! In other words, you don't have to dereference at all, you just have to transform the index into the data you want.

When you store all possible values of something in a table, this always happens: your index becomes merely an encoded version of the data itself, so storing the data becomes unnecessary in the first place. This why in the real world, indices are only useful for sparse data (e.g. all web pages you've visited, not all web pages that could exist, or even all that do exist).

Title: Is a memory of all possible permutations of a kilobyte block and pointers possible?

Body:
This is a hard enough idea to wrap my head around and I would greatly appreciate any edits/help to get it more readable for those in-the-know.

Is it theoretically possible to have a hard drive that has saved on it one copy of every possible binary permutation of one kilobyte and then have the rest of the system simply create pointers to these locations?

Would a system made such a way be any faster than simply having information stored directly?

To explain another way, say instead of having sentences:

"Hello, I'm Bob." and "That sandwich looks delicious."

...stored on the hard drive, we would have all permutations of the alphabet and other characters up to some number (say, 1000 characters or so), and then have store our sentences as something like:

[Pointer#21381723]


问:
Open Source PHP Encoder
Are there some recomendations on Open Source or Free PHP Encoder systems?
Is something available?

答: If what you look for is a compiler, not encoder, check out hiphop. Otherwise, it is rather hard to write an encoder that would sufficiently hide details about your PHP script, so don't put high hopes in obfuscators beings secure or making your code un-recoverable.</p>

ContentLicense: CC BY-SA 2.5

Title: Open Source PHP Encoder


问:
Too many REST API calls on a page?
A web app designed with highly modular, small components (in this case using AngularJS directives but could just as easily be WebComponents, ReactJS components, or any other technology).  Components often have asynchronous REST API calls, upon initialization or upon user interaction.  This design is causing many API calls per page (sometimes 20+).  Is there any problem with this design?  Some are suggesting we condense the API calls into larger client-side services that act as singletons.  So 10 API calls may be reduced to 1, even though a page may only use a portion of that data.  Are there any red flags, or problems with this design?  Which should be preferred?</p>

答:
Browsers limit the total number of concurrent requests

https://stackoverflow.com/questions/561046

So yes, there is a problem with this design. However I think the accepted response is to move to a web-sockets implementation where you use a single connection, but with many message types to communicate with the server

Title: Too many REST API calls on a page?


答:
As others have already pointed out, you have 2^8192 possibilities for a 1k block. This means you would need 8192 bits to encode the address of a block if all blocks addresses are encoded with the same amount of bits, so your addresses would be 1k long. You wouldn't have gained anything except adding a layer of indirection so you wouldn't gain any performance.

If you wanted to have shorter addresses, you would have to encode some blocks with a short address and some with longer ones and make it so that long ones don't appear that often, and you are now simply compressing data (probably with something like a Huffman code). That would require knowledge of the data you're storing before storing it or regular changes in the encoding. It would also probably be less efficient than other compression algorithms which use blocks of varying length.


答:
I think the answer by Niall is good and the accepted answer is correct, but wish to add a bit in the vein of using Singletons.

The Singleton pattern is a bit like Communism. It looks good on paper, but when you mix it with people things tend to fall apart.

The thing is that the Singleton pattern isn't, inherently, an anti-pattern.  It's more that most (naive) implementations of it tend to skim over important aspects or cause possible issues.

For example, in C++, a globally initialized Singleton can be allocated pretty much whenever sometime before the main loop starts.  Combining multiple Singletons this way means you have no idea what order they will initialize relative to each other.  The order of cleanup is similarly arbitrary (but generally the reverse of the order they were initialized in).
(There are SOME basic rules for this, but mostly it's left up to the nasal demons.)

Global and readily accessible objects also tend to end up veering into the realms of a God Class, which is very much an anti-pattern.  Ideas like "I already have a Manager class, I'll just stick it there," are easy and the solution is quick.  This is a case of Technical Debt.

A controlled Singleton managed correctly can be very useful and not cause problems, but they are a more difficult pattern to get right than people tend to expect. The worst part is that the examples out of text books tend to teach really bad habits for Singletons.

For your specific case, since you have no state and don't need to load or unload, you don't need an object. A static function or equivalent should suit your needs.

And, since I can't comment (shakes fist), I want to second Niall's point on understanding what a pattern solves and where it works.  I'd also recommend researching how it works and how best to implement it, as implementing a pattern correctly is at least as important as choosing the right pattern.


问:
Single tracking algorithm for many carriers
When it comes to tracking packages from a multitude of carriers, is it possible to wrap a globally accepted way of pulling tacking status or must I write support for each carrier we deal with?

I have software which processes EDI documents. I've implemented a ways to automatically invoice based on the status reported back from a tracking number. Our first trading partner uses only UPS -- simple. Done. No problem. The second however throws all of that out the window. It's all about freight with a select group of carriers and most of them support an API BUT I would like to not have to write, implement and update for every single one we must support. Not to mention the users can add more carriers.

Currently we'll only shuffle between 3 types of carriers so there isn't THAT much, but who knows? We could have 10 Trading partners by the end of the year and have to support 50% of the major carriers in our region. This work can grow quickly and I'm looking for a possible solution, if one exists.

答:
What you've described sounds like a classic case for using the adapter pattern.

At a higher level, the pattern is there to protect your application from changes occurring in external interfaces.  It also serves as a convenient mechanism to introduce new external interfaces while minimizing the change to your core application.

Here's a diagram to help visualize how things will lay out.

Click to expand

The darker blue PackageTracking component represents your global function that you would call in order to track a package.

The green Shipping Interface represents a common set of functionality that you need to have from all of your shipping carriers.

The lighter blue Carrier _ Wrapper represents the wrapper functions you'll need to write to interface with each carrier.

Unfortunately, there's no easy way around having to write code against the particular EDI API of each carrier. The upside of this approach is that you only have to touch the one carrier's wrapper when they make changes. You don't have to touch the other carriers' wrapper code.


问:
Is this a candidate for Singleton?
I have an external thermometer connected via USB that is controlled by my SW. Different parts of my system will use it but never at the same time (all in one thread). However, it is a single device communicating over an established connection so for some reason I think either its method (GetTemperature) should be static or I could do it as Singleton.
I will be happy for suggestions. Thanks</p>

答:
From a maintainability and code reuse stand point I'd say no, however that assumes a lifetime to the project.

While you could use a Singleton here, adding more thermometers would become messy and difficult. Using RAII is definitely the way to go, and Singleton does that, but I'd still make the thermometer instance a non-global object.

If the code will live longer than the immediate task, it would be more useful to build a class which encapsulates all of the thermometer communication, as you would with a singleton, but then wrap/store that inside of a singleton.  This is a little more complicated, but makes it much easier to reuse the code later and expand into having more thermometers.

Title: Is this a candidate for Singleton?


问:
What are you telling yourself if you can't understand new concept, paradigm, feature ...?
Programming always required to learn new concepts, paradigms, features and technologies and I always have been failed at first attempt to understand new concept what i encounter. I start to blame and humiliate myself without remember before how i understood new concept which i hadn't understand it before.

I can hardly stop to tell myself "why i cant understand ? Am i stupid or idiot ? Yes, i am stuppiiddddd!!!"

What your inner voice tells if you can not understand new concept after spend long time till been tired or hopeless ?

How do you handle your self-esteem in such situations ?

答:
I remind myself of something my father had on his wall in college -- (as far as I can tell, he originated the quote...)

No concept is so difficult that it cannot be conquered by the repeated attacks of an ordinary mind.

This can be encouraging to those of us with ordinary minds.


问:
Problems in QA Environment
At least few times a week I have to track down a bug that would not occur in a production\client environment. 95% of the time I can tell that its a QA configuration\environment problem just by looking at the ticket. But, many times Im asked to track down and prove that its a QA issue and not an actual bug.

How common is this?

If QA doesnt know when there is a legitimate bug then I think there is a big problem.

I've suggested setting up the QA environment myself to avoid these problems.

Who should setup the QA environment? Developers or QA?

答:
All the companies I have worked at (and I know I am lucky because of this) have had QA that is set up exactly the same as production so I am unsure how common those sorts of bugs are.

Deployments to QA were completed the same way deployments to prod were.  If there were deployment scripts the only thing that changed between UAT and PROD were server names.

I would say that bugs in QA are actual bugs with the software and are legitimate.  A bug resulting from a configuration error is still a bug (even though a configuration change can fix it).  I would keep track of all the bugs that are a result of configuration differences between QA and PROD and then ask management for funds (if needed) or authorization to make changes so that the configuration between QA and PROD is the same.  If the environment is set up for every QA test work on the scripts so that it is the same as prod.

By having our QA and PROD set up the same we could try out new configuration changes in QA and see if it would introduce any bugs or cause performance issues.  With out QA and PROD matching that would not have been possible.

As for who should set up the QA environment?  It has varied from the devops team (responsible for all environments) to the server admins (responsible for all environments).  However this will differ for every company.

Do not question the "legitimacy" of bugs.  If some one finds a "bug" it means something did not work correctly.  If it is because of a configuration issue either fix the configuration issue in QA or handle the issue in code if you expect that configuration issue to be present in PROD.  As soon as you start to question the "legitimacy" of bugs things will get missed by QA and some major catastrophy will happen in PROD, Murphy likes to rear his head.

Title: Problems in QA Environment


问:
Deployment of application which uses apache 2.0 libraries
I need to publicly deploy web app which uses apache 2.0 libraries. The license obliges me to provide credits in case of redistribution. Do I need to do this in such a case. Is it considered redistribution? Are there any best practices in such a case?

What about javascript parts?

答: In general, a deployment is not a distribution. You are obliged to follow the rules for distribution only if you're allowing people to download and install your application.


问:
How does the LLVM compiler treat arithmetic operations in parentheses?
When it sees the parentheses, does it have the machine do the operations in the parentheses first, or does it distribute out the parentheses?

Like, if I have the following line of code:

```<code>int i = 2 * (a + b)
</code>```

does it compile like this code:

```<code>int c = a + b
int i = 2 * c
</code>```

答: It works "as-if" the addition is done first, followed by the multiplication.  Under the as-if rule, any number of machine instructions that produce the correct result can be used, and in fact it's almost certain that a multiplication instruction will not be used by any optimizing compiler.</p>


问:
Forcing Cache Refresh

I'm updating an existing tomcat web application to read certain resources from a REST API. Currently the application reads them from flat files. Since the application is very critical, I added a caching layer so that the objects returned by REST API are always available.

In the service layer of API client, if the request item is not found in the Cache, the request will be sent to the actual API, the response is put in MapDB cache and returned to caller. The startup listener calls a bunch of APIs with different parameters so that all data is now in MapDB cache. I do not set a expiration on the items in cache because I want them to always available unless I refresh on demand.

The problem is Web App and API client are different projects. Since API client decides to read from Cache or API, I'm not able to force refresh cache value from the application.

Should I add another parameter to function calls I make to API client or

```<code>Object obj = ServiceFactory.getLanguageService()
                    .getLanguagesFromApi(env.getName(),
                            env.getEnvironmentType(),
                            env.getPhase().toString(), null, true);
</code>```

The last "true" parameter indicates forcing cache refresh.

Should I get the existing value in cache to a temporary variable, delete the entry, make API call, if no value is returned because of some error, put the entry back into the cache.

```<code>        String key = ClientUtils.concatenateList(
                Arrays.asList(ClientConstants.RESOURCE_LANGUAGE,
                        env.getName(), env.getEnvironmentType(),
                        env.getPhase(), null),
                ClientConstants.CACHE_KEY_SEPERATOR,
                ClientConstants.NULL_STRING);

        Object cachedElement = ClientCache.getCache().get(key);
        if (cachedElement != null) {
            ClientCache.getCache().delete(key);
        }

        Object obj = ServiceFactory.getLanguageService()
                .getLanguagesFromApi(env.getName(),
                        env.getEnvironmentType(),
                        env.getPhase().toString(), null);

        if (obj == null) {
            ClientCache.getCache().put(key, cachedElement);
        }
</code>```

What is the cleaner way to do this ? I feel adding parameters about caching to function makes it clumsy and add dependencies - like getUsers(String country, boolean forceAPIrequest). But deleting and adding same entries may also waste resources and heap space, causing GC over time. Also, App will directly access Client Cache to do these operations.

All this is based on strong assumption that our REST API is unreliable. Web App should not have any down time.

答: The call that you do first does s complete cache refresh yes?  If do then why not schedule it.. If the full request comes back fine then flush and re instantiate the cache... </p>

Title: Forcing Cache Refresh


问:
Why does Objective-C store objects on the heap instead of on the stack?
I have a basic understanding of what a "stack" and "heap" are. You use a stack to store items in memory that should be read and/or removed in a last-in-first-read/removed manner. To steal another example from someone else's Website, you use it to perform arithmetic operations involving PEMDAS. You also use a stack to store return addresses for functions. Like a heap, the CPU uses a pointer to find the item to be read and/or removed.

You use a heap when you don't need the computer to store objects in a sequential order in memory.

My question is, what's the deal with the * pointer in Objective-C? Local variables in a method are going to get deallocated when the method's done anyway, so why not just use the stack instead?

I'm going to go out on a limb here and say that the short answer is that because stacks have a limited memory, Objective-C wants to keep its stack usage to a minimum.

答:
To go into a little bit of history, it was not always the case that stack based objects were forbidden in Objective-C. Michael Rutman told me (in 2009) that this happened in NeXTSTEP version 2.0 back in 1990.

"This was the release where zones were introduced, new was replaced with alloc/init, and stack based objects were no longer allowed."

I see from my copy of Brad Cox's "Object Oriented Programming", dated 1987, that alloc and init don't exist and new is used to allocate arrays.

Zones were introduced to allow the programmer to specify which region of memory was to be used for the object; this would imply (although to know for sure I'd have to bother Michael Rutman or Brad Cox) that the reason they were no longer simply put on the stack was to allow (or force) the programmer to think about where they were putting their objects.

alloc had a sister function, allocWithZone. alloc would use a default zone, while allocWithZone would allow the programmer to specify the zone to use for this object. Faster memory for some, slower memory for others, group things together as needed.

The GNU Step manual,  http://andrewd.ces.clemson.edu/courses/cpsc102/notes/GNUStep-manual.pdf , in section 3.1.2, discusses it and states that it was for performance reasons.

So while the reason for it today might be as people discuss in other answers, this would suggest that originally it was about giving programmers control for performance reasons. For example, it allowed programmers to group together objects that would be used together frequently, to cut down on paging and the like.


问:
Why don't "multi-infinite" list comprehensions work with lazy evaluation?
As a simple demonstration of the efficiency of Haskell style, I thoughtlessly ran the following:

take 100 [(a, b, c) | a <- [1..], b <- [1..], c <- [1..], a^2 + b^2 == c^2]

This should be a way of deriving the first 100 Pythagorean triples, with duplicates. In practice however, it never halts, because the algorithm itself defies lazy evaluation.

To think about it in terms of actual implementation, the following should be something similar to how the list comprehension is actually evaluated, in an imperative style:

```<code>results = []
for (a = 0; a < ∞; a++) {
  for (b = 0; b < ∞; b++) {
    for (c = 0; c < ∞; c++) {
      if (a^2 + b^2 == c^2) {
        results[] = [a, b, c]
      }
    }
  }
}
</code>```

When written like this, it becomes obvious that the function can never yield results, because infinite time will be spent testing whether 1^2 + 1^1 == c^2, as only the innermost for loop will advance, and a and b will remain '1'.

The common solution in this particular case is to constrain the values of the smallest two variables to that of the largest:

take 100 [(a, b, c) | c <- [1..],a <- [1..c], b <- [1..c],a^2 + b^2 == c^2]

However, this seems like an obvious oversight for implementors of the language. When you think about it, any list comprehension with more than one infinite source of search space will never halt, for the same reason, except some will yield useful results when (1, 1, x) is useful. There are questions discussing this problem, but most discuss specific cases, rather than the problem overall. Why isn't fixing this within the language with a different iteration pattern trivial?

答:
A short answer: You just need to use a different monad (omega), for lists this is working as intended.

To elaborate: For list comprehensions, you want to have the results in a specific order. And while for your use-case you want a different order, for others this order is what they need and want.

The problem is that if you do diagonalization, like the omega monad does, it's quite hard to decide how to sequence it. Consider that:

The lists might contain complex sequences, like powers of two. How would you prioritize then arithmetic vs geometric sequences?

The lists might contain values of any type, which might not even be ordered.

Given the above, even if you have a guarantee that you'll eventually find all combinations in a finite time, in practice this will still mean that one particular one might take really long to find.

With omega and monad comprehensions you can easily express your problem as

```<code>test :: [(Integer, Integer, Integer)]
test = take 100 $ runOmega [(a, b, c) | a <- each [1..]
                                      , b <- each [1..]
                                      , c <- each [1..]
                                      , a^2 == b^2 + c^2]
</code>```

However you'll see that even though it eventually finds all triples, it won't find the "good ones" in a reasonable time.

For a real use-case, I'd suggest to use the LogicT monad. There you have explicit control over diagonalization using interleave and >>-.

Body:
A short answer: You just need to use a different monad (omega), for lists this is working as intended.

To elaborate: For list comprehensions, you want to have the results in a specific order. And while for your use-case you want a different order, for others this order is what they need and want.

The problem is that if you do diagonalization, like the omega monad does, it's quite hard to decide how to sequence it. Consider that:

The lists might contain complex sequences, like powers of two. How would you prioritize then arithmetic vs geometric sequences?

The lists might contain values of any type, which might not even be ordered.

Given the above, even if you have a guarantee that you'll eventually find all combinations in a finite time, in practice this will still mean that one particular one might take really long to find.

With omega and monad comprehensions you can easily express your problem as

test :: [(Integer, Integer, Integer)]
test = take 100 $ runOmega [(a, b, c) | a <- each [1..]
                                      , b <- each [1..]
                                      , c <- each [1..]
                                      , a^2 == b^2 + c^2]

However you'll see that even though it eventually finds all triples, it won't find the "good ones" in a reasonable time.

For a real use-case, I'd suggest to use the LogicT monad. There you have explicit control over diagonalization using interleave and >>-.


答:
One likely sequence of machine instructions for a regular, orthogonal, 3-address RISC CPU would go something like this:

```<code>LOAD_MEMORY &a -> register01
LOAD_MEMORY &b -> register02
INT_ADD register01, register02 -> register01
LOAD_CONSTANT 1 -> register02
BIT_SHIFT register01, register02 -> register01
STORE_MEMORY &i, register01
</code>```

Also, if a is a local variable and the compiler can prove that it won't be accessed after this, it might put i and a at the same memory address.

For a CISC CPU with a more complex irregular instruction set, there might be shift instructions that work on memory, and take constants, and add instructions that work on memory, then it would look something like this:

```<code>INT_ADD_MEM &a, &b -> &i
BIT_SHIFT_MEM_CONSTANT &i, 1 -> &i
</code>```

Again, a and i may have the same address, if a is local and unused afterward.

Title: How does the LLVM compiler treat arithmetic operations in parentheses?

Body:
When it sees the parentheses, does it have the machine do the operations in the parentheses first, or does it distribute out the parentheses?

Like, if I have the following line of code:

```<code>int i = 2 * (a + b)
</code>```

does it compile like this code:

```<code>int c = a + b
int i = 2 * c
</code>```

Body:
One likely sequence of machine instructions for a regular, orthogonal, 3-address RISC CPU would go something like this:

LOAD_MEMORY &a -> register01
LOAD_MEMORY &b -> register02
INT_ADD register01, register02 -> register01
LOAD_CONSTANT 1 -> register02
BIT_SHIFT register01, register02 -> register01
STORE_MEMORY &i, register01

Also, if a is a local variable and the compiler can prove that it won't be accessed after this, it might put i and a at the same memory address.

For a CISC CPU with a more complex irregular instruction set, there might be shift instructions that work on memory, and take constants, and add instructions that work on memory, then it would look something like this:

INT_ADD_MEM &a, &b -> &i
BIT_SHIFT_MEM_CONSTANT &i, 1 -> &i

Again, a and i may have the same address, if a is local and unused afterward.


答:
In Objective-C, objects are reference counted. An object goes away when there is no reference to it anymore. On the other hand, objects on the stack go away when the function call ends. Can you see the problem? If the last reference goes away before the function call ends, you waste memory. If the function call ends while there are still references to the object, you have a much more serious problem.

Now you could have objects both on the stack and on the heap, as C++ does. Is it worth it? There is added code complexity, and what do you actually gain? Memory allocation on the heap is fast - after all, if everything is allocated on the heap, you have some rather strong motivation to make it fast.

Title: Why does Objective-C store objects on the heap instead of on the stack?

Body:
I have a basic understanding of what a "stack" and "heap" are. You use a stack to store items in memory that should be read and/or removed in a last-in-first-read/removed manner. To steal another example from someone else's Website, you use it to perform arithmetic operations involving PEMDAS. You also use a stack to store return addresses for functions. Like a heap, the CPU uses a pointer to find the item to be read and/or removed.

You use a heap when you don't need the computer to store objects in a sequential order in memory.

My question is, what's the deal with the * pointer in Objective-C? Local variables in a method are going to get deallocated when the method's done anyway, so why not just use the stack instead?

I'm going to go out on a limb here and say that the short answer is that because stacks have a limited memory, Objective-C wants to keep its stack usage to a minimum.


问:
Is O(log n) + O(log n) = O(n)?
We know that binary search takes O(log n) in Big O notation but if we need to run twice an algorithm of O(log n), would it be the same as O(n) in time complexity?

For example, if I have a method to calculate the first occurrence of a number in a sorted array with duplicates and another method to calculate the last occurrence. Each of both methods takes O(log n) to run, so at the end if I want to know the number of occurrences of an specific number in the array using both methods I would have a O(2 log n), right? Can we infer that O(2 log n) is equal to O(n) or lower?

答:
Both O(log n) and O(2 log n) are subsets of O(n). They are also both equal to O(log n).

You must remember that O(log n) is a set, it is (informally) "the set of all functions that don't grow significantly faster than f(x) = log x". So, all of the following are true

O(log n) = O(2 log n)

O(log n) ⊂ O(n)

O(2 log n) ⊂ O(n)

∀f: f ∈ O(2 log n) ⇒ f ∈ O(n)

You can easily verify that by plugging the functions into the definition of O(g).

Unfortunately, there is a lot of abuse of notation going on in this regard. For example, f ∈ O(g) is often written f = O(g), even though it doesn't make sense: f is a function, O(g) is a set of functions. An apple can never be equal to a set of apples! Likewise, it is often written that O(f) = O(g), when what is really meant is that O(f) ⊂ O(g). And lastly, people will sometimes claim that f(n) = 2n is an element of O(n) but not of O(n²), which is wrong. O(n) is a subset of O(n²), so any function that is in O(n) is also in O(n²).

Title: Is O(log n) + O(log n) = O(n)?


问:
Any reason behind hyphens in a GUID?
Just when I generated a GUID, I found some hyphens in between the character and also at specified intervals

```<code>8b55fec7-c987-4e7b-abad-16e5aaea9b53
</code>```

Is there any story behind this?

Note: My intention is to remove those hyphens as I am adding this GUID to a filename and our filename should only be aplhanumeric.

答:
The hyphens are always placed at the same position, so you won't lose any information (or unique-ness) by removing them.

See Stack Overflow: Why are there dashes in a .NET GUID? for a detailed explanation.

Title: Any reason behind hyphens in a GUID?


答:
So I just bought this USB hub with seven ports. And I had this great idea to put a thermometer into each room of my home. The problem is... there's a singleton object!

The other problem is that other people don't have a thermometer at all. In that case a singleton is one object too many.

Title: Is this a candidate for Singleton?

Body:
I have an external thermometer connected via USB that is controlled by my SW. Different parts of my system will use it but never at the same time (all in one thread). However, it is a single device communicating over an established connection so for some reason I think either its method (GetTemperature) should be static or I could do it as Singleton.
I will be happy for suggestions. Thanks</p>


问:
Which sorting algorithms have a different worst case complexity than their average case?
I'v been working on sorting for a while now but I can't figure these two questions apart,  I'm kind of getting mixed up somewhere ... Somebody help

a) Which sorting algorithms have a different worst case complexity than their average case?

b) Which sorting algorithms have a different best case complexity than their average case?

答: There are implementations that first check if the array starts or ends with a sequence of elements in ascending or descending order, and takes advantage if many such elements are found. So best case is linear (if the array is mostly sorted in ascending or descending order). What the average case would be can be highly debatable. </p>


答:
For large values of n, the constants are ignored in Big O notation.

Hence

O(log n)+O(log n)=O(2log n)->O(log n)

Title: Is O(log n) + O(log n) = O(n)?

Body:
We know that binary search takes O(log n) in Big O notation but if we need to run twice an algorithm of O(log n), would it be the same as O(n) in time complexity?

For example, if I have a method to calculate the first occurrence of a number in a sorted array with duplicates and another method to calculate the last occurrence. Each of both methods takes O(log n) to run, so at the end if I want to know the number of occurrences of an specific number in the array using both methods I would have a O(2 log n), right? Can we infer that O(2 log n) is equal to O(n) or lower?


答:
No, O(log n) + O(log n) is not O(n). It is still O(log n). When we have a big-O formula multiplied by a constant, it is equivalent to the value without the multiplied constant. So:

```<code>O(k * g) = O(g)
</code>```

where k is a constant, non-zero factor and g is a bounding function.

An O(log n) operation is an operation that takes a number of steps proportional to the logarithm (the base just contributes a constant factor) of the size of the input, denoted by n. When you have multiple operations of the same big-O order, you can add them together as you have done, and come out with something like O(2 * log n), but big-O notation is not concerned with constant multiplicative factors, so we ignore the 2 and write O(log n).

The reason we are not concerned with constant factors* is that we are examining an algorithm's potential for growth based on input size. We don't use it to calculate the exact number of steps, just to see how the number of steps might grow.

Let's look at some real numbers to give ourselves a less mathematically abstract example. We have an algorithm that runs in O(log n) time and takes exactly log2(n) steps. We have a method where we run it once with an input of size 8. It takes 3 steps to complete. We have another method where we run it twice, so it takes 6 steps to complete. This is not the comparison we care about, though. We want to know about the growth. We run the first method again with an input size of 16. It takes 4 steps to complete, +33% more steps. We run the second method with an input size of 16. It takes 8 steps to complete, also +33% more steps. We can see that, though the number of steps is different, the growth is the same between the functions. The rate of growth is O(log n) despite how many times it is called, and it is the rate of growth that we are interested in.

* We are also not concerned with lower-growth bounding function parts, so O(n + log n) is equivalent to O(n).

Title: Is O(log n) + O(log n) = O(n)?

Body:
No, O(log n) + O(log n) is not O(n). It is still O(log n). When we have a big-O formula multiplied by a constant, it is equivalent to the value without the multiplied constant. So:

O(k * g) = O(g)

where k is a constant, non-zero factor and g is a bounding function.

An O(log n) operation is an operation that takes a number of steps proportional to the logarithm (the base just contributes a constant factor) of the size of the input, denoted by n. When you have multiple operations of the same big-O order, you can add them together as you have done, and come out with something like O(2 * log n), but big-O notation is not concerned with constant multiplicative factors, so we ignore the 2 and write O(log n).

The reason we are not concerned with constant factors* is that we are examining an algorithm's potential for growth based on input size. We don't use it to calculate the exact number of steps, just to see how the number of steps might grow.

Let's look at some real numbers to give ourselves a less mathematically abstract example. We have an algorithm that runs in O(log n) time and takes exactly log2(n) steps. We have a method where we run it once with an input of size 8. It takes 3 steps to complete. We have another method where we run it twice, so it takes 6 steps to complete. This is not the comparison we care about, though. We want to know about the growth. We run the first method again with an input size of 16. It takes 4 steps to complete, +33% more steps. We run the second method with an input size of 16. It takes 8 steps to complete, also +33% more steps. We can see that, though the number of steps is different, the growth is the same between the functions. The rate of growth is O(log n) despite how many times it is called, and it is the rate of growth that we are interested in.

* We are also not concerned with lower-growth bounding function parts, so O(n + log n) is equivalent to O(n).

ContentLicense: CC BY-SA 4.0


问:
Coordinate access to resource between workers
I have a database accessed by an several servers, let's call them workers. These workers take one item from the database, do some operations on it and then update it back into the database. The workers are also volatile, there can be any amount of them and they can die/start at any time.

My problem is coordination of resources across workers. I want to ensure that there aren't 2 workers working on the same item. I also want to ensure that if a worker dies while he was working on an item, this item will be released to another server (either immediately or via timeout).

How can I ensure this coordination? I know that I can implement some custom logic myself using database transactions and some kind of server discovery/monitoring.

This seems like a common problem but I am having a hard time googling for a solution, I don't know which terms to search for.

答:
Why not use built-in database synchronization? All enterprise-class SQL databases are ACID-compliant, as are most NoSQL databases.

Worker acquires a task. You may need to use a DB-specific syntax for this:

UPDATE task SET status = 'in process', worker = (this worker's ID) WHERE status = 'new' LIMIT 1

SELECT * FROM task WHERE status = 'in process' AND worker = (this worker's ID)

Worker works on the task: it can periodically update a timestamp on the task to indicate it is not timing out.

Worker finishes: it updates the task to set its status to complete and save the results wherever they need to go.

I would have a job running in the background to look for timed out tasks and reset them. This would likely be simpler than adding extra logic to the SELECT query.

There are likely existing solutions out there to do this. Using them may be easier than rolling your own depending on the complexity of managing the tasks and your requirements. Specifically, something like Hadoop would likely both get the job done and be overkill for what you describe here.


答: Long sequences are very hard to parse for humans, hence the hyphens. But GUID itself is just a number, so you can drop them. </p>

Title: Any reason behind hyphens in a GUID?

Body:
Just when I generated a GUID, I found some hyphens in between the character and also at specified intervals

```<code>8b55fec7-c987-4e7b-abad-16e5aaea9b53
</code>```

Is there any story behind this?

Note: My intention is to remove those hyphens as I am adding this GUID to a filename and our filename should only be aplhanumeric.


问:
Should the main functions of a program be in a separate object?
For a class project in Introduction to Object Orientated Programming, we are creating a simple game.

This game has two main menus. I was just wondering what the best practice for organizing these are. Should I have these functions in a separate object or should I keep these as separate methods?

To me it makes more sense to create separate methods for each and call it in the main like this

```<code>public static void main(String[] args)
{
    // call sub module and create objects
}
</code>```

Any help on this? I figure it will be coming up a lot throughout programming so I want to know the best practices for handling this.

答:
I would suggest storing your menu structure in some hierarchical data structure:

```<code>//C# sample
//You can replace the object initializers with constructors in the class,
//In C# 6.0, you can also create an Add extension method taking three parameters, for use with the collection initializer
//    https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6#extension-add-methods-in-collection-initializers

class MenuEntry {
    public string Title {get;set;}
    public Action Action {get;set;}
    public List<MenuEntry> Subentries {get;set;}
}

var entries = new List<MenuEntry> {
    new MenuEntry() {Title = "TopLevel1", Subentries = new List<MenuEntry>() {
        new MenuEntry() {Title = "SecondLevel1", Action = () => SecondLevel1()},
        new MenuEntry() {Title = "SecondLevel2", Action = () => SecondLevel2()}
    },
    new MenuEntry() {Title = "TopLevel2", Subentries = new List<MenuEntry>() {
        new MenuEntry() {Title = "SecondLevel3", Action = () => SecondLevel3()},
        new MenuEntry() {Title = "SecondLevel4", Action = () => SecondLevel4()}
    }
}
</code>```

Then all you need is a single recursive function to render each MenuEntry to the corresponding UI element, and connect the Action to that element.

All else being equal, it is simplest to group the called methods (SecondLevel1, SecondLevel2) together, either in the same class as the main method, or in a separate static class for all these methods. However, it may be more appropriate to keep some or all individual methods together with the appropriate parts of the application: e.g. a StartNewGame method might belong with the Game class.

Body:
I would suggest storing your menu structure in some hierarchical data structure:

//C# sample
//You can replace the object initializers with constructors in the class,
//In C# 6.0, you can also create an Add extension method taking three parameters, for use with the collection initializer
//    https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6#extension-add-methods-in-collection-initializers

class MenuEntry {
    public string Title {get;set;}
    public Action Action {get;set;}
    public List<MenuEntry> Subentries {get;set;}
}

var entries = new List<MenuEntry> {
    new MenuEntry() {Title = "TopLevel1", Subentries = new List<MenuEntry>() {
        new MenuEntry() {Title = "SecondLevel1", Action = () => SecondLevel1()},
        new MenuEntry() {Title = "SecondLevel2", Action = () => SecondLevel2()}
    },
    new MenuEntry() {Title = "TopLevel2", Subentries = new List<MenuEntry>() {
        new MenuEntry() {Title = "SecondLevel3", Action = () => SecondLevel3()},
        new MenuEntry() {Title = "SecondLevel4", Action = () => SecondLevel4()}
    }
}

Then all you need is a single recursive function to render each MenuEntry to the corresponding UI element, and connect the Action to that element.

All else being equal, it is simplest to group the called methods (SecondLevel1, SecondLevel2) together, either in the same class as the main method, or in a separate static class for all these methods. However, it may be more appropriate to keep some or all individual methods together with the appropriate parts of the application: e.g. a StartNewGame method might belong with the Game class.


问:
How do you safely refactor in a language with dynamic scope?
For those of you who have the good fortune not to work in a language with dynamic scope, let me give you a little refresher on how that works. Imagine a pseudo-language, called "RUBELLA", that behaves like this:

```<code>function foo() {
    print(x); // not defined locally => uses whatever value `x` has in the calling context
    y = "tetanus";
}
function bar() {
    x = "measles";
    foo();
    print(y); // not defined locally, but set by the call to `foo()`
}
bar(); // prints "measles" followed by "tetanus"
</code>```

That is, variables propagate up and down the call stack freely - all variables defined in foo are visible to (and mutatable by) its caller bar, and the reverse is also true. This has serious implications for code refactorability. Imagine that you have the following code:

```<code>function a() { // defined in file A
    x = "qux";
    b();
}
function b() { // defined in file B
    c();
}
function c() { // defined in file C
    print(x);
}
</code>```

Now, calls to a() will print qux. But then, someday, you decide that you need to change b a little bit. You don't know all the calling contexts (some of which may in fact be outside your codebase), but that should be alright - your changes are going to be completely internal to b, right? So you rewrite it like this:

```<code>function b() {
    x = "oops";
    c();
}
</code>```

And you might think that you haven't changed anything, since you've just defined a local variable. But, in fact, you've broken a! Now, a prints oops rather than qux.

Bringing this back out of the realm of pseudo-languages, this is exactly how MUMPS behaves, albeit with different syntax.

Modern ("modern") versions of MUMPS include the so-called NEW statement, which allows you to prevent variables from leaking from a callee to a caller. So in the first example above, if we had done NEW y = "tetanus" in foo(), then print(y) in bar() would print nothing (in MUMPS, all names point to the empty string unless explicitly set to something else). But there is nothing that can prevent variables from leaking from a caller to a callee: if we have function p() { NEW x = 3; q(); print(x); }, for all we know, q() could mutate x, despite not explicitly receiving x as a parameter. This is still a bad situation to be in, but not as bad as it probably used to be.

With these dangers in mind, how can we safely refactor code in MUMPS or any other language with dynamic scoping?

There are some obvious good practices for making refactoring easier, like never using variables in a function other than those you initialize (NEW) yourself or are passed as an explicit parameter, and explicitly documenting any parameters that are implicitly passed from a function's callers. But in a decades-old, ~108-LOC codebase, these are luxuries one often does not have.

And, of course, essentially all good practices for refactoring in languages with lexical scope are also applicable in languages with dynamic scope - write tests, and so forth. The question, then, is this: how do we mitigate the risks specifically associated with the increased fragility of dynamically-scoped code when refactoring?

(Note that while How do you navigate and refactor code written in a dynamic language? has a similar title to this question, it is wholly unrelated.)

答:
To state the obvious: How to do refactoring here? Proceed very carefully.

(As you've described it, developing and maintaining the existing code base should be difficult enough, let alone attempting to refactor it.)

I believe I would retroactively apply a test-driven approach here. This would involve writing a suite of tests to ensure the current functionality remains working as you start refactoring, firstly just to make the testing easier. (Yes, I expect a chicken and egg problem here, unless your code is modular enough already to test without changing it at all.)

Then you can proceed with other refactoring, checking that you haven't broken any tests as you go.

Finally, you can start writing tests that expect new functionality and then write the code to make those tests work.


问:
Front-end structure of large scale Django project
Few days ago, I started to work in new company. Before me, all front-end and backend code was written by one man.

As you know, Django app contains two main directories for front-end: /static - for static(public) files and /templates - for django templates

Now, we have large application with more than 10 different modules like: home, admin, spanel, mobile etc.

This is current structure of files and directories:

FIRST - /static directory. As you can see, it is mixed directories with some named like modules, some contains global libs.

one more:

SECOND - /templates directory. Some directories named like module with mixed templates, some
depends on new version =), some used only in module, but placed globally.

and more:

I think, that this is ugly, non-maintainable, put-in-stress structure!

After some time spend, I suggest to use this scheme, that based on module-structure.

At first, we have version directories, used for save full project backup, includes: /DEPRECATED directory - for old, unused files and /CURRENT (Active) directory, that contains

production version of project.

I think it's right, because we can access to older or newer version files fast and easy.
Also, we are saved from broken or wrong dependencies between different versions.

Second, in every version we have standalone modules and global module.

Every module contains own /static and /templates directories. This structure used to avoid broken or wrong dependencies between different modules, because every module has own js app,  css tables and local images.

Global module contains all libraries, main style-sheets and images like logos or favicon.

I think, this structure is much better to maintain, update, refactoring etc.

My question is:

How do you think, is this scheme better than current? Can this scheme live, or it is not possible to implement this in Django app?

答:
The points that look ugly to me:

Why not a Version Control System? Keeping versions on the local file system is not pretty. You can use versioning systems and add 3rd party javascript/css libraries too so added/removed/replaced javascript and css files will be trackable. You go go back or forth between revisions and check the differences easily.

It is hard to develop a software whose modules needs different versions of the same 3rd party software. If your admin module need jQuery X while
Products module needs jQuery Y, then you have problems. It is hard to maintain and it would be only you who knows why each module need specific version of jQuery X and  why it can not run under jQuery Y. Since you have a full copy of each deployment on your local drive, You probably will not remember why A module is needing a specific bootstrap version. For different js/css files which are specific to a single module, you can create static directory under each application and place application-specific files in here. See this post as a reference

Django have a well-planned template structure. You can do the same as you did to static files. You may have templates directory under each application and palce application-specific templates in here.

Having application-specific templates and static directories is up to the developer. If having all files under the same directory looks ugly then you can choose the application-specific solution. Django will handle them both nicely. Especially if you have a lot of applications then you may have name collusions if all of your templates and static files are under the same directory.

Current form is much better than the old one. But I am sure you may get more better ideas if you check the Django docs and check SO/programmers for similar situations and solutions.


问:
Time slot generation based on available technicians
Consider an Organization which provides technicians for different types of jobs.

Each job type varies in completion time and technician count. For e.g., Job type 1 requires 2 technicians and 1 hour to complete and job type 2 requires 1 technician and 30 minutes to complete. All technicians are available all the time (Organization working time is 09:00-18:00) unless they are assigned any jobs.

A customer can request the service online and an available time slot should be displayed based on the selected job type.

There are no other constraints like minimum shift or maximum shift per technician, and also assume that all technicians are  equally skilled.

What is the best possible way to generate the time slot?

答:
As usual, there is no silver bullet that can be declared as the best way.

That being said, I suggest you take a look at constraint-based scheduling. These types of scheduling problems are very common and constraint programming has had tremendous success in solving and more importantly describing them.

With a CP solver you can specify the constraints similar to what you have already described in your post (of course there's some syntax to adhere too) and the solver does the hard work of calculating the best time slots.

Depending on your constraints and your fitness function (i.e. you may want to tell the solver why one solution is better than another) this can get more and more complicated. CP is sometimes considered as a programming paradigm, so it does have a lot of breadth and depth you can get lost in. But starting with any of the available solvers and playing around with it to check if this might be worthwhile in your case certainly is possible in a limited scope. If the problem is not too involved, I found that most people get a hang of how to encode it and let it be solved rather quickly.

The good and most important imho thing with a CP solution is that you have a direct representation of your constraints which a) helps for communication and b) makes changes much easier.


问:
Why isn't there a true "Date-Only" data type?
I'm so ridiculously frustrated with having to use DateTime values for data sets that are truly "just a day." Birthdays being the most-common example, but this comes up in business applications all the time.

I've gotten used to just setting the Time part of "date-only" records to "noon" (which avoids the date ever changing no matter the timezone). This seems like a hack, and I'm forever finding bugs from junior devs that trip over this issue.

Time is always relative to a fixed point. 4PM is 4 hours post meridian, or noon. The sun's highest point in transit is observable, and allows us to set up a coordinate system. 3 hours before noon (Ante Meridian), 2 hours after noon, 1441899402938 milliseconds since January 1, 1970. To people raised in a Cartesian world, this is second nature.

But our Calendar predates Descartes. My argument is that it is more properly thought of as a enumeration over which a modulo function is applied. Monday follows Sunday, and so on until you get to the fact that Sunday follows Saturday. There is no positive and negative, it is a modulus, or absolute value.

Similarly with years repeating. Every 365 days (or so) there are several special days for me: birthdays, anniversaries, childrens' birthdays, etc. etc. Business scheduling applications are rife with examples of meetings every seven days, first Tuesday of the month, etc. Just because we CAN map this onto a floating point number, and in truth mapping it onto said number solves a LOT of problems that are really difficult the old way, but that doesn't mean it's the only way to do it.

Awareness and understanding of the "square peg in a round hole" nature of using DateTimes to store Dates makes you a better programmer in my opinion.

Is there value in an application explicitly intended as a scheduling application in defining a Date class, or is "set all times to noon" the best approach? What issues might there be with using DateTime and setting the Time component to Noon?  Can timezone shifting be accounted for in such an approach? I've used MomentJS, but I think that's just a better Date class.

答:
I'm so ridiculously frustrated with having to use DateTime values for data sets that are truly "just a day." Birthdays being the most-common example, but this comes up in business applications all the time.

This is probably because calendar are complicated and used in so many different ways that nobody has been able to figure a class which is simple yet general enough to be useful in many fields.

The date type commonly found in programming languages can be used to accurately date transactions in a computer system. Other use-cases are likely to require a custom library.

Here is a short lists of facts about calendars, demonstrating their complexity – most of them are historical, so if you are restricting your attention  to dates after 1.1.1970, you will not be affected by this. However if your application needs to work with dates occurring before the late 19th century, then these facts would matter.  Possible use-cases are historical databases of all sorts (books, genealogy) but also assets of large companies or organisation still in activity today.

All these facts are quoted from the excellent FAQ found in the calendar library for OCaml written by Julien Signolles.

The Julian calendar was introduced by Julius Caesar in 45 BC. It was
in common use until the 1500s, when countries started changing to the
Gregorian calendar (section 2.2). However, some countries (for
example, Greece and Russia) used it into the 1900s, and the Orthodox
church in Russia still uses it, as do some other Orthodox churches.

Switching from the Julian to the Gregorian calendar did not occur uniformly, and depending from the year of change, 10 to 13 days has been dropped. For instance in France 9 Dec 1582 was followed by 20 Dec 1582 and in Greece 9 Mar 1924 was followed by 23 Mar 1924.

Even in the modern era, many different calendars are used (Gregorian, Orthodox, Islamic and Chinese) to quote a few, which all use different ways to compute years and anniversaries or the date religious celebrations.

Now you hope for a date type bundled with operations useful for general business operations. I guess there is no such a thing as general business operations. For instance, in the finance world, we need to compute:

Year fractions (like “6 months” corresponds to “0.5”), which are used in conjunction with an interest rate to compute the actual interest on a loan for a given term. There is 6 to  10 recipes to compute these fractions, each differing in the ways they handle the length of a leap year, the position of the period with respect to the last day of February and the duration of a month.

Date rolling, when computing anniversaries, we use a business calendar and a rule (picked from a set of more than 6 different rules) to shift an anniversary from an holiday to a business day.

For people working in the finance industry, any calendar type not implementing all these functions and rules is useless.  It is likely that many other industries have other types of habits and conventions requiring custom computations on calendar.

Is there value in an application explicitly intended as a scheduling application in defining a Date class, or is "set all times to noon" the best approach? What issues might there be with using DateTime and setting the Time component to Noon? Can timezone shifting be accounted for in such an approach? I've used MomentJS, but I think that's just a better Date class.

If you need to keep track of a single calendar day, the best way is probably to use a large integer representing the Julian day of that calendar day. Algorithms to convert back and forth from the Julian day to the calendar day – described with year, month and calendar – are widely known and thoroughly tested, so that you can easily implement them in your application – and figure out whatever rule is pertinent in your case to compute the anniversary of an event occurring on some 29th Februray.


问:
What are the differences among the .NET certification exams?
I am a .NET developer using WPF and ASP.NET MVC and I was hoping to pass some kind of certification exam.

There seems to be four exams but I am unable to understand what the differences are even with Microsoft's definitions:

MCPD

MCAD

MCSD

MTA

How do they relate to each other? Is there a natural progression path through the certification exams? What version of .NET are they suited for?

答:
Both MCAD and MCSD are certifications for older versions of the .NET framework (.NET 1.1 to the best of my memory)
MCAD was kind of a stepping stone to MCSD - 3 exams were needed to get a MCAD and another additional 2 papers would help you attain MCSD (the additional papers were related mostly to MS products like SQL / Biztalk etc)

MCPD papers were earlier targeted towards .NET 3.5 (EDIT: I checked the MS site and this set of certifications have been upgraded for .NET 4.0. Basically, what it looks like is that now there is a separate set of MCPD papers targeted to .net 2.0 / 3.5 / 4.0).

MCPD-EA is supposed to be the closest equivalent to the erstwhile MCSD certification.

The MTA is new to me. Based on what i read from the MS site, seems to be an entry level certification. The MS site says
Help demonstrate your knowledge of technology fundamentals by earning a Microsoft Technology Associate (MTA) certification. Earning the MTA certification can help you stand out when you submit college and internship applications by helping to prove your commitment
and understanding of a variety of entry-level technology concepts

The MCSD/ MCPD exams are all time bound - usually around 60 mins but it can vary.
The number of questions also usually varies for the different exams.

Regarding the resources, usually, there is an entire series of  MS press books -called Self paced training kits one for each exam - these books are not indepth but they are useful to gauge the scope of the topics that are usually covered for each exam.

As for preparation / difficulty, it is subjective.
Based on my experience, these exams focus more on breadth rather than depth and hence cover a wide variety of topics and personally, i found it worthwhile to use the self paced training kit as a reference and specifically look up certain topics like deployment / tools  etc for which my practical knowledge was largely superficial

Regarding the validity of these exams, frankly, i would take it with a pinch of salt.
There are just too many sites out there selling the question + answers for these (and most other) certifications and largely, seeing one of these certifications listed on a potential candidate's resume means nothing to me.

OwnerDisplayName: John Mitchel


问:
Deployment Environment Responsibility
This might be not technical but rather process driven query. Help me redirect to right forum if this is not the place to ask such question.

Typically in a project, we have a deployment environment where development team deploy the code for testing purpose. Testing team executes test cases on the environment.

But I have seen projects where there are multiple environments for different teams to test on, and when I get to understand that what's the point? I do not see any reason than to have multiple environments.

Two environments:

1. Lower Environment-  Developers can use this environment to test their code( this environment will be an exact replica of higher environment where Internal and External testing will happen). We use SVN and checkin the code.

2. Higher Environment - where multiple testing team can test which from my experience seems stable env. to test on.

But we have lot of environments....and time to time support has to give on different environment.

But I see multiple environment where testing happens with no apparent concrete reason. My question is who's responsibility to support multiple environments? I find it difficult for development team to work on supporting multiple environments apart from regular dev activities, Unit test case preparation, get clarification from the design or business on User story.

Any suggestions would be highly appreciated.

答:
Several examples I came across:

The production and test/dev environments have different set of features. As an example, a project I worked on included scheduled updates of state. In the production environment, the updates were scheduled once a week, but in development and testing environments, we needed the state to change more frequently or be triggered manually. So we had a kill-switch for manually changing the state.

Avoiding conflicts between the tests run by different teams. When looking for defects, being able to reproduce the defects is extremely important. Having multiple teams working on the same environment can make this difficult, as the steps revealing the defect might be the result of the actions of multiple teams (accidental) crossing. JUnit, the famous unit testing framework, creates separate objects for each of the test cases. This is done so that every test case is isolated and doesn't affect other test cases. The same principle applies here. Instead of coordinating the testing plans of multiple teams, each team works on a different environment.

Different platforms, hosting the product. If the product supports multiple platforms, it should be tested on each of them. Moreover, it should be tested on each version of each supported platform (Windows XP, Windows 7, Windows 8, etc.). Each requires separate environment. The upgrade scenarios both of the product and the platform increase the number of necessary environments as well.

Stress-testing, stability testing. Some tests require that the product is under high workload. Others test the stability, so that the environment has to be up for a large period of time. These types of tests require dedicated environments.

Conflicting settings. For example, the team testing the localization has to change the language of the environment multiple times. This can cause inconvenience for others teams, which aren't familiar with all of the supported languages.

In my experience, the QA team is responsible for creating and maintaining the environments. But to do this properly, the QA team needs to have a clear list of the points above, including the supported deployment types, platforms, settings and features to be able to create a proper test plan.

Title: Deployment Environment Responsibility


问:
Inheritance when following the Repository Pattern in PHP
I am trying to build a PHP application using the Repository Pattern but I'm not sure how I should implement the save method.

I have an abstract class called ItemRepository which have the following method:

```<code>abstract class ItemRepository
{
    public function save(Item $item);
}
</code>```

Where Item also is an abstract class.

Now I want to implement the class MovieRepository which extends ItemRepository. Here I want to save instances of the Movie class which extends Item.

Though doing it like this in PHP

```<code>// MovieRepository.php
class MovieRepository extends ItemRepository
{
    public function save(Movie $movie)
    {
        ...
    }
}
</code>```

gives the following error

Declaration of MovieRepository::save() should be compatible with ItemRepository::save(Item $item)

What is the right way to do this?

答:
Drop the Item/Movie types from the save() method:

```<code>abstract class ItemRepository
{
    public abstract function save($item);
}

class MovieRepository extends ItemRepository
{
    public function save($movie)
    {
        ...
    }
}
</code>```

PHP is primarily dynamically typed language and while I understand the desire to use types as much as possible, in this case PHP's type system is not strong enough to express what you need. In other languages (Java, C++), you could express it with generics, which PHP lacks.

Body:
Drop the Item/Movie types from the save() method:

abstract class ItemRepository
{
    public abstract function save($item);
}

class MovieRepository extends ItemRepository
{
    public function save($movie)
    {
        ...
    }
}

PHP is primarily dynamically typed language and while I understand the desire to use types as much as possible, in this case PHP's type system is not strong enough to express what you need. In other languages (Java, C++), you could express it with generics, which PHP lacks.