问:
Too many parameters to data processing class constructor
I have a conceptually simple application: data comes in as small encrypted packets, they decrypted and validated, some are stored in the database, some rules are applied, and a reply might be encrypted and sent. Packets arrive at a rate of high hundreds of thousands per thread per second, so performance is a consideration. I am leaving out most of the performance elements here to focus on the design.

Main elements: packets arrive in a queue and each processor thread gets one at a time:

take ownership of a single incoming packet (at a time)

decrypt

use a factory to construct the appropriate packet class

packet saves itself to database (often multiple inserts)

rule engine run by some types of packets, resulting actions queued

packet may generate 1 or more replies to 1 or more recipients

One problem is that each processor thread owns a bunch of helper instances that get passed into the constructor of the packets. Those helper classes are often painful to create  (like the database connection), so I don't want the packet to construct them. During decryption I accumulate information about the packet from the database so I want to pass that in too. That's a lot of parameters.

I've ended up with 15 parameters to the PacketClass constructor and growing. That seems excessive, but I can't see an elegant solution.

The constructor looks like this:

```<code>PacketClass(database, cryptoEngine, {more references} ...
   packetDataBlob, packetBlobSize, {packet source information},
   {database values passed rather than repeating lookups}...
</code>```

At some stage I intend to cache the database info that gets looked up during decryption because there's only going to be a million or so records and that lookup will be a bottleneck. But for now there's ~50 bytes in 6 values that get looked up for each packet then passed into the constructor from one SELECT query. Once the cache is operational those will become a single const reference but for now they're not.

Options:

make all the utility class references global or thread-global as per the IOC/service locator trend

pass a reference to the owning thread/processor to each packet giving quite horrid linking

wrap the params into a couple of data classes and pretend there's nothing to see.

split the PacketClass constructor into construct-with-references and initialise-with-data methods (does this even count as a solution?)

some brilliant solution I haven't thought of

Can anyone suggest options?

Robert Harvey suggested in chat splitting the processing into a PacketProcessorClass for each PacketClass so that behaviour and data are separated. That way much of the processing is done to the PacketClass in the processor thread rather than inside the packet as it is now. I'm going to work through that design over the weekend. Other ideas are also welcome.

New Design:

```<code>PacketClass( packetDataBlob, packetBlobSize, {packet source information},
   {database values passed rather than repeating lookups}...

PacketClassProcessor(database, cryptoEngine, {more references})
PacketClassProcessor.Process(Packet)
</code>```

Performance considerations: this might even be faster than the current setup. I expect to be able to cache most of the ProcessorClass instances, so there's not that construction overhead. And the PacketClass could become a C struct so again no constructor overhead except for any collections it contains... and I can cache at least one of those (the "rules that apply to this packet' one).

(I edited out some fluff too)

答: It sounds like you need the classic refactoring Introduce Parameter Object, which might be where Robert Harvey is heading with PacketClassProcessor. Basically, if a large clump of variables are passed around between multiple methods, wrap all (or some) of them in a parameter class.</p>


问:
MVC Controller - keeping methods small
I'm reading uncle Bob's Clean Code and it completely revolutionizes my programming style. In this book author claims that best methods are small methods. What about controller's action methods in modern frameworks? Do you try to follow the "20 lines per method" rule, or you delegate some tasks to private methods?  I don't ask about things that you can move to services and external classes, sometimes there are situations that you cannot avoid bigger code in action. Another question and another look at this problem - do you tract controller class as (some sort of)  special class with only action methods,  or just another regular class with private methods and own fields along with action methods?  </p>

答:
or just another regular class with private methods and own fields along with action methods?

Yes. It's just a class, i.e. keep methods small and refactor as needed into private sub-methods (or delegate to other classes, if appropriate).

Personally, 20 lines is a good upper limit, but I try for less. Occasionally, e.g. for complex algorithms with lots of state, you might go way over 20.

ContentLicense: CC BY-SA 3.0

Title: MVC Controller - keeping methods small


问:
Microservice architecture: single database owned by a single service?
We're rebuilding a system in a microservice archiecture. I know the standard practice for SOA is to have each individual service responsible for its own database.

However, does it make sense to have one 'database' service responsible for handling a monolithic database (i.e. holding users, orders, inventory, etc in one db)? Is this something that's considered reasonable?

Or is the expectation that users, orders, inventory will all have their own separate databases and according services? If that's the case, how do I handle it when I want to do a simple relational query like ordering a list of inventory by how many orders we've had for each item?

Edit: not duplicate. to clarify (from comments):
I understand that it's bad to share databases among multiple microservices. my question is whether having a big central database managed by a single microservice is a bad idea, or if it's critical that the internal system's data be decoupled itself

答:
However, does it make sense to have one 'database' service responsible
  for handling a monolithic database (i.e. holding users, orders,
  inventory, etc in one db)? Is this something that's considered
  reasonable?

I think this is a mistake to make a service (or whatever) in SOA or any other architecture responsible for a database or a part of database or a table or whatever database part you can imagine.

Service is about fulfilling a user (or may be other service's) request. Database interaction is only a secondary to that. Microservice servers a group of requests, not a group of tables.

It is my understanding, that services are usually designed to use a dedicated database just to ensure maximum decoupling. This way service data is physically separated from the data of another service. Also this decision allows you to easily move service to a new platform (just move service app server + database into another machine).

You can use single database if you will find other means of keeping your services decoupled and if you will not be too troubled with moving a specific part of your database to, say, another machine (figuring out which part of database belongs to which service is sometimes not easy).


问:
Decorator design pattern in swift
I'm reading "Head first design patterns" (here you can find exact example mentioned in book)

While going through Decorator design pattern, everything was crisp and clear until I stumbled into this

They are explaining decorator using

Extensions.
I don't think extending a class through 'Extensions' results in decorator design pattern since we can't add properties to classes. As I understand, key to decorator is it ability to wraps other objects infinity, this is not possible here, although we can add functionality to existing class without inheriting it.

Delegation.
Delegation here is completely out of context. Isn't delegation itself a design pattern?

答:
You can't add stored properties, but you can add computed properties.  A computed property can act just like a stored property.  In fact ObjC provides a handy set of calls to make that if not actually easy...well, at least not hard.

Performance might not be where you want it, but if performance is a big deal let the profiler tell you when you should give up on "pattern implementation purity " and move some properties into the class proper.

ContentLicense: CC BY-SA 4.0

Title: Decorator design pattern in swift


问:
Architecture for my Java application
I try to create small Java tools to help me at my work every now and then. Usually these do not have to be pretty and I find myself coding a single, sometimes massive, Java class. However, now my plan is to create a tool for myself that would parse certain files for me and create desired output as a result. I'd like this tool to have a GUI and I'd like to use Swing for that. However, I cannot seem to get my head around the concept of how I should devise my application - classes, packages and such.

I plan on having a simple Swing GUI with a file chooser, the application will crunch the input (this logic is fairly clear to me), and output the result summary into the GUI and ask the user to specify a directory path where to save the output file(s). How should I separate my application logic into separate classes? I would be fairly happy if someone could point be to a great article or something of the sort; what does the application main class usually include, how should the GUI be separated from the application logic, and so on.

I do not want to cram all my code into a single class anymore, since it does not make my code scale nor easy to maintain.

答:
When it comes to design, it is usually a good idea to have an idea of design patterns. This will help you better visualize the best way to structure your application. It is worth noting though, that you should choose the design patterns depending on what you need to do, and not try to force your design to conform to a specific design pattern.

At the very least in your case, you will need to have at least 2 classes, one being the Swing front end, and another being the processing/parsing mechanism. The UI is usually the main class and it takes care of starting/loading other modules.

Exposing a series of methods (within the UI class) which facilitate the printing of data to the user usually also helps, since the logic part of the program (in your case, the second class) would not need to be concerned with how should its output be rendered. So for instance, you could have a method in your UI class called showResultToUser(String result). This will in turn use the appropriate mechanisms to display it in a meaning full way to the user.

If you will be parsing multiple file structures, in my opinion you could create a separate class for each file type, this would help you keep your code segregated, thus making it easier to change one piece without breaking the rest.

Also, segregating UI with logic can make it easier to have the logic execute in separate threads. It is never recommended to have heavy operations, such as file processing, database operations etc on the UI thread (Event Dispatcher Thread). Launching the parsing mechanism in a separate thread (and maybe pass a reference to the UI class as well, so that the logic can do something particular when it is finished) would allow your application to remain responsive.

Title: Architecture for my Java application


问:
Algorithm Space and Time Complexity with Consideration for I/O (eg cache)
Is there an expression of performance for an algorithm or data structure that attempts to consider cache and other hardware concerns?

Context: in my class we're looking at binary trees and it seems like it would be extremely difficult to optimize data retrieval with the structure.  I know B-Trees address this problem, but I haven't seen a formal analysis of how much speed is improved considering some amount of cache.

答:
I've never applied it to rigorously prove the cost of some algorithm or data structure but I believe what you're looking for is the Idealized-cache model. The idea is to do Big O analysis where the cost is the number of cache block transfers instead of atomic machine instructions. E.g. Traversing an array under that model is O(n/B) where n is the number of elements and B is the cache block size. (Technically n is the number of bytes the array elements take up, but the difference between that and the number of elements is a constant factor, which Big O notation ignores.)

You might want to read the paper Cache Efficient Functional Algorithms, which applies this kind of analysis in the context of a purely functional language. I'm sure there's plenty of other papers as well; cache-efficient and cache-oblivious data structures and algorithms are an active research topic.

In a language with a generational garbage collector you make use of the heuristic that things that are allocated sequentially in time will generally end up adjacent in memory. The reason for this is that generational garbage collectors usually allocate sequentially in the youngest generation, and when a collection happens the live objects will be compacted and possibly moved to an older generation as well. When this happens the object graph will generally be traversed in depth-first or breadth-first order, but either way objects end up adjacent to other objects they point to.

If your language's garbage collector is non-generational and also non-moving/copying/compacting I don't know what you'd do, but then your performance is probably screwed either way since your memory is fragmented.

On the subject cache-efficient trees, you might want to read Improving RRB-Tree Performance through Transience which talks about a vector/list implementation using trees whose nodes have 31 or 32 children each.


问:
Is it redundant and unnecessary to do file backups of a repository that has a remote repo?
Is it redundant and unnecessary to periodically backup the files in a Git repo, that also has a remote repo?  My understanding is all repositories are full backups.  So an individual developer with a local repo pushing to a remote repo is two full copies of the data in the repo.

I guess there's always the chance that both copies (local and remote) can be lost, but that seems rather unlikely.

Is it just the paranoid IT person inside of me that still wants to do a backup of the files to different media?  Is that completely useless and unfounded?

答:
You're right that once a local repository is pushed to a remote location, both locations contain the successive revisions. Moreover, if somebody mistakenly erases some of the files and pushes this change to the remote repository, you can still recover those files with ease from the history.

What is the risk for both copies to be lost? It depends on the infrastructure in use. Consider those scenarios:

If you're using GitHub, for instance, the risk is extremely low.

On the other hand, if the remote location is your corporate server, then maybe it is not truly remote.

What if it is in the same building where you work? What if a fire destroys both the server and your computer?

If the server is really geographically remote, could it be that a virus will propagate to both the corporate server and your machine?

Explore how remote location handles the repository. If it's a corporate server, contact the IT guy who knows how backups are managed (if he don't know the answer, this is a bad sign).

How often do they make backups?

Do they have off-site backups?

Have they ever tested their backups, or they are waiting for a disaster to occur to discover that the latest working backup was made three years ago?

Even with solutions such as GitHub, on a bad day, you are at risk of losing your internet connection and at the same time screw your repository files. If waiting for internet connection to come back is not an option, then a local backup is a viable option.

It all comes to the cost of backup versus the risk of losing everything. You're probably already making a regular backup of your machine, backing up everything. Including your source code makes sense, even if you evaluated the risk of a disaster to be infinitely small.


问:
Pattern for validating rules having different signatures
I have a class in charge of responding to an input event and maybe triggering another event. To decide, it has several rules to check.

I'm trying to get away from a class looking like this:

```<code>public class Translator {
    public void maybeTranslate() {
        if (!condition1 || !condition2 || !condition3) {
            return;
        }

        // All rules have passed
        translate();
    }
}
</code>```

I'd like this class to know that it has rules to pass, but not know about the implementations of rules. My attempt was to transform it like so:

```<code>public class Translator {
    private Rule[] rules;

    public Translator (Rule[] rules) { this.rules = rules; }

    public void maybeTranslate() {
        for (Rule rule : rules) {
            if (!rule.passes()) {
                return;
            }
        }

        translate();
    }
}
</code>```

where a Rule has this interface:

```<code>public interface Rule {
    boolean passes();
}
</code>```

Here comes my problem: I now have a new rule that takes in a parameter. Its passes method would require a String parameter. Is my foundation wrong with this new requirement? I don't see how I can adapt this pattern to accommodate rules having various parameters.

This parameter would indicate the source of the input event. I can modify maybeTranslate to receive this value from whoever calls it, and change the Rule interface to be boolean passes(String str). Only now, the majority of my rules are getting a parameter they don't care about.

This is in the context of an Android app, where Translator would be instantiated on different fragments.

UPDATE: Some changes from my original question.

This Translator will be used on multiple screens. There is only one screen active at a time, and each screen can have a different set of rules.

Instead of making a rule take in a parameter and act differently, I created multiple screen-dependent rules (ScreenOneRule, ScreenTwoRule, etc.).

Now I would use the class like this:

```<code>public class ScreenOne {
    Translator translator;

    public Screen(Translator translator) { ... }

    public void onSomeEvent() { translator.maybeTranslate(); }
}
</code>```

and I would create the set of rules for ScreenOne in my IoC configuration (this is an attempt at pseudo code):

```<code>Rule[] screenOneRules = new Rule[] { SharedRule1, SharedRule2, ScreenOneRule1 }
ScreenOne screenOne = new Screen(new Translator(screenOneRules))
</code>```

This solves my problem, though I feel like the design is not perfect. What if I get a rule later on that depends on a value only known after the screen has been instantiated? For example, say a rule needs to know the (x,y) coordinates of where the user tapped on screen to trigger onSomeEvent. I have a feeling ScreenOne would need to construct the rules itself in onSomeEvent. I think this is coming back to my original question.

In that case, I would want to have the instantiation of rules somewhere else. Is the solution to have a factory like this?

```<code>public class RuleFactory {
    public Rule[] getRulesForScreenOne(int x, int y, String anotherParameter) {
        return new Rule[] { new SharedRule1(x, y), new SharedRule2(anotherParameter) };
    }
}

public void onSomeEvent() {
    Rule[] rules = RuleFactory.getRulesForScreenOne(x, y, str);
    translator.maybeTranslate(rules);
}
</code>```

At that point, Translator would not receive rules in its constructor. I can't put my finger on it, but I feel like the factory implementation isn't right. Something about that method name.

答:
In a similar situation I am using a state machine. The fact that your rule needs the source of the event tells me that your rule must consider the context of the event, i.e. the state your are in.
In my suggested state machine scenario your model would be like this:

You represent the "world" in your application by defining the possible states with relevant quantifiable variables. (e.g. screen name is 'xy', or userLoggedIn == true, and so on).

You add a generic function that checks which state you are in.

You register possible transitions for every state (possible steps/events that will bring your application into another state).

You create the logic (a heuristic function) to prioritize available transitions so your program code will choose one of the possible events.

I know, it is a short answer compared to the size of the topic, but I think you can go on with these keywords and learn more with the help of google.

Hope this helps.


问:
How should I structure modules in an Angular.js application?
I am fairly new to Angular.js, and one that confuses me is how to best use modules in an application.  It seems to me that modules can contain any of the other common constructs in AngularJS (controllers, directives, filters, services, etc.), but from here I am unsure which module(s) should contain which things.

Should I have one module that contains all of the other objects in my application? This seems the easiest to set up, but this smells of the God Object Anti-Pattern to me.

Should I divide modules up by types of objects? i.e. one module for controllers, one for directives, etc.?

Should I divide them by use? So that all directives, services, and filters that are used for part of the application are together?

some other strategy I haven't yet seen / thought of?

Any help would be greatly appreciated.

答:
Probably you are not new and have the answer by now. The links from @KeesDijk and @Aaron should provide you a comprehensive answer already.

Since I also had the same question before, this answer could be useful for those who start learning Angularjs.

Should I have one module that contains all of the other objects in my application? This seems the easiest to set up, but this smells of the God Object Anti-Pattern to me.

You have the answer yourself. Unless it is a really small app, having a single module usually not ta good choice.

Should I divide modules up by types of objects? i.e. one module for controllers, one for directives, etc.?

Let's say you have 4 modules for controllers/directives/service/filter each, once you have more than 30 components. Each module have 7-8 components. As you have larger application, you will end up like the previous option.

Also, if you want to reuse one functionality, like user management, you will need to have dependency on several modules.

Should I divide them by use? So that all directives, services, and filters that are used for part of the application are together?

This is the most common recommended practices. One module/folder per one functionality. It is easier to reuse, read (by other programmers), and can scale as the application grows.

Reusability is also better, you can just have a dependency on module 'user'.

some other strategy I haven't yet seen / thought of?

Based on the previous option, you can have variants.

It can be useful to structure your module in a nested way by sub-functionality. For example, you can have module 'user' which contains 'user-list' and 'user-edit' modules. (See https://github.com/angular-app/angular-app for example)

You can have common/shared module separated out of the rest and prefix them. Ex. 'common', 'common-model-user', 'common-ui-modal', etc.


问:
When to make a method part of an interface or a concrete implementation?
I create an interface for database access to a MySQL database.  Currently, this is the only way to access day, but to make it easier to test and in the event that the data access might change, I used an interface.

However, now I am faced with the dilemma of which methods I should put on the interface and which methods I should put on the concrete implementation" directly.  Is there a rule of thumb for this?

I will give an example below where I have some CRUD operations for a ICar interface, but then some other utility functions that are just on the concrete implementation.  Should these be on the interface as well?  I wouldn't want a user to have to implement every method if they didn't need to?

```<code>interface ICar {
   Car GetCar(int id);
   void DeleteCar(int id);
   void InsertCar(Car car)
   Car UpdateCar(Car car);
}

class Car : ICar {

  Car GetCar(int id) {}

  void DeleteCar(int id) {}

  void InsertCar(Car car) {}

  Car UpdateCar(Car car) {}

  // methods not on interface, but should they be

  public string GetCarVIN(Car car) {}

  public string GetCarColor(Car car) {}

  public string GetCarMake(Car car) {}

  public string GetCarModel(Car car) {}

  public string GetCarOwner(Car car) {}
}
</code>```

答:
However, now I am faced with the dilemma of which methods I should put on the interface and which methods I should put on the concrete implementation" directly. Is there a rule of thumb for this?

Split the difference and create an abstract class.


问:
Abstract classes and constants
I have two classes that share a lot of code and are conceptually variations on a common class. So I want an abstract class that contains all their common code and then they can each inherit from it and fill in the stuff unique to them. However I am running into a problem with constants and static methods. Basically, the relationship I have is like this:

Class A and Class B both have some methods that don't depend on an instance of the class, just the value of a set of constant strings. Basically as such:

```<code>const string onePrefix;
const string differentPrefix;

static string ConvertMethod(string input)
{
  input.replace(onePrefix, differentPrefix);
}
</code>```

The method code is the same between the two classes, so I would like to have it in the abstract class. But the actual values of the two constants are different between the two classes. But abstract constants are not a thing you can do as far as I can tell so I'm not sure how to go about structuring my classes to make this work like I want it to. I've considered just not having the values be constants, but they are used in my constructors before an instanced object is created.

答:
Try a readonly variable.  MSDN says this:

The readonly keyword differs from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, although a const field is a compile-time constant, the readonly field can be used for run-time constants, as in this line: public static readonly uint l1 = (uint)DateTime.Now.Ticks;

Title: Abstract classes and constants


问:
SQL - for some attributes specific to different clients' users, how to handle schema?
I have clients, each of whom have an app with a bunch of users.

Their user data could be pretty different, but there is also a lot of overlap. Ex: all their users have "gender" and "age" and plenty of other things, so it makes sense to have a standard user_table schema across all clients (with a column for each attribute).

But there is also user information specific to each client. Ex. one might have "relationship_status" for their users, which other clients do not have. While another has "height" for their users, which other clients do not have.

How to I design a schema that is appropriate for both of these cases at once?

One possibility is to somehow have a different schema for each client, but this seems like it could be unnecessary hassle. Another possibility is to put every column in the standard schema across all clients, but then the columns that are unique to a single client would just sit empty for all the other clients.

答:
In my honest opinion having different sets of tables for different sets of users will add complexity to your code by having 'X' amount of SQL queries.  Because for one schema you'll have one SQL Query string for grabbing the data from there, but for another schema you'll have another SQL Query string from grabbing data from there.

Plus I think it makes it harder to maintain.

If this schema is supposed to be a general schema/table containing user data then I find it easier having one schema only and for the columns that don't apply to a specific user then just put a default N/A text.

This may provide a database table with more N/A's in it than you like.  But I think that's a trade off well worth it by making sure you only have one set of SQL Queries for just that one schema.


问:
Setting and getting values from a x-y graph
I have a bunch of x-y graphs given to me and I need to be able to transform them into some kind of data structure from which I will be able to get Y with X value.

The problem is, though that I have 4, at max 5 values of Y given to me, and my X values can range up to 9000. So the information I have is something of the form

```<code>Point # X       Y
1       1000    100
2       3250    460
3       6000    320
4       6500    300
</code>```

My idea initially was something like:

```<code>function getY($x){
    $data[1000] = 100;
    $data[3250] = 460;
    $data[6000] = 320;
    $data[6500] = 300;

    if(isset($data[$x])){
        return $data[$x];
    }

    $minKnown = null;
    $maxKnown = null;

    foreach($data as $_x => $y){
        if($_x < $x){
            $minKnown = $_x;
        }

        if($_x > $x){
            $maxKnown = $_x;
            break;
        }
    }

    return $data[$minKnown] + (($x - $minKnown) / ($maxKnown - $minKnown)) * ($data[$maxKnown] - $data[$minKnown]);
</code>```

}
    }

This function I just wrote to illustrate my idea. Basically if a point is not defined but somewhere between 2 known points, assuming there are no curves between the two points get the value that co-responds to the position of X between the two known values of X. I'm not even sure if my verbal explanation is actually correct or not but I guess that's what I wrote the function for.

Anyway, I was thinking, since graphs something that's widely used, are there any better ways of doing this, and I'm hoping there are otherwise I might turn out to be smarter than I thought, which is scary.

答:
Since you said, that you assume that there are no curves, the graph itself would probably look like a stock development. So I would try a vector calculation approach.
With the data you gave in your example you would get 3 vectors defined by two points. (To generalize it, you would get one vector less then you got points.)

In your example:

Vector1: Point1->Point2 (Point2[x] - Point1[x], Point2[y] - Point1[y])

Vector2: Point2->Point3 (Point3[x] - Point2[x], Point3[y] - Point2[y])

Vector3: Point3->Point4 (Point4[x] - Point3[x], Point4[y] - Point3[y])

With values:

Vector1: (3250 - 1000, 460 - 100) = (2250, 360)

Vector2: (6000 - 3250, 320 - 460) = (2750, -140)

Vector3: (6500 - 6000, 300 - 320) = (500, -20)

Now the standard linear function has the form y = m*x + b. The vector itself won't need the b. So for Vector1 it is: 360 = m * 2250

Resolved for m we get: m = 360 / 2250 = 0.16
Now we get back to the original line between P1 and P2, which will require a value for b.

We get this now with: 100 = 0.16 * 1000 + b => b = -60
With that we know each y value between Point1 and Point2 will be defined by this equation: y = 0.16 * x - 60.

You can check this by simply inserting the values of one of the points into the equation:
P1 100 = 1000 * 0.16 - 60

P2 460 = 3250 * 0.16 - 60

Code example:

```<code>$vector1x = $Point2->X - $Point1->X;
$vector1y = $Point2->Y - $Point1->Y;

$m1 = $vector1y / $vector1x
$b1 = $Point1->y - $Point1->x * $m1
// do the same for the other points as described.
</code>```

Now when you get a value for x which you want to get the y value of do sth like this:

```<code>function getY($x)
{
    if($x >= $Point1->X && $x <= $Point2->X)
    {
        $y = $m1 * $x + $b1;
    }
    else if($x <= $Point3->X)
    {
        $y = $m2 * $x + $b2;
    }
    else if($x <= $Point4->X)
    {
        $y = $m3 * $x + $b3;
    }
    else
    {
        throw new Exception("Cannot calculate value with given data!");
    }
    return $y;
}
</code>```

I hope this approach serves your needs and helps you in solving the problem.

Body:
Since you said, that you assume that there are no curves, the graph itself would probably look like a stock development. So I would try a vector calculation approach.
With the data you gave in your example you would get 3 vectors defined by two points. (To generalize it, you would get one vector less then you got points.)

In your example:

Vector1: Point1->Point2 (Point2[x] - Point1[x], Point2[y] - Point1[y])

Vector2: Point2->Point3 (Point3[x] - Point2[x], Point3[y] - Point2[y])

Vector3: Point3->Point4 (Point4[x] - Point3[x], Point4[y] - Point3[y])

With values:

Vector1: (3250 - 1000, 460 - 100) = (2250, 360)

Vector2: (6000 - 3250, 320 - 460) = (2750, -140)

Vector3: (6500 - 6000, 300 - 320) = (500, -20)

Now the standard linear function has the form y = m*x + b. The vector itself won't need the b. So for Vector1 it is: 360 = m * 2250

Resolved for m we get: m = 360 / 2250 = 0.16
Now we get back to the original line between P1 and P2, which will require a value for b.

We get this now with: 100 = 0.16 * 1000 + b => b = -60
With that we know each y value between Point1 and Point2 will be defined by this equation: y = 0.16 * x - 60.

You can check this by simply inserting the values of one of the points into the equation:
P1 100 = 1000 * 0.16 - 60

P2 460 = 3250 * 0.16 - 60

Code example:

$vector1x = $Point2->X - $Point1->X;
$vector1y = $Point2->Y - $Point1->Y;

$m1 = $vector1y / $vector1x
$b1 = $Point1->y - $Point1->x * $m1
// do the same for the other points as described.

Now when you get a value for x which you want to get the y value of do sth like this:

function getY($x)
{
    if($x >= $Point1->X && $x <= $Point2->X)
    {
        $y = $m1 * $x + $b1;
    }
    else if($x <= $Point3->X)
    {
        $y = $m2 * $x + $b2;
    }
    else if($x <= $Point4->X)
    {
        $y = $m3 * $x + $b3;
    }
    else
    {
        throw new Exception("Cannot calculate value with given data!");
    }
    return $y;
}

I hope this approach serves your needs and helps you in solving the problem.


问:
What kinds of Open-Source licenses are NOT OK to use internally in a corporation?
I have recently learned about several cool open source add-on tools and libraries for Microsoft Visual Studio. The tools just help you be more productive; the libraries would get linked into the corporate code base.

I have listed all these cool tools and libraries on a spreadsheet and I'm going to run down the type of license each one is under. So far, amongst my cool libraries, I see MIT, BSD, Apache License Version 2.0. However, there could be more in the future.

How can I find out (or better yet, can you just list) the popular licenses which are NOT compatible with internal corporate use (not to be distributed outside the company)? And for an extra thank you, can you say or point to an explanation. I'm not a lawyer and reading the fine print of these licenses gives me a headache.

I want to be prepared to explain why using the allowable licenses is OK.

答:
In general, the legalities in licensing that can occur as a result of the use of open-source software boil down to two factors:

Commercial use, and

Distribution.

Distribution means "conferring" software to a third party outside the organization.  Since you say you only use the software internally, legal mechanisms like "copyleft" (the term used for the viral portion of the GPL license) probably don't apply to your organization.

Commercial use (or other arbitrary restrictions) are a different matter.  Simply read the license carefully, and determine if any of those restrictions apply to your organization.  In particular, permissive licenses such as Apache, MIT and BSD have few, if any, restrictive conditions; these licenses are ideal for "internal use."

It sounds like your company is reluctant to use open-source software.  Many companies believe that they must completely own their software and other intellectual property, and so they have policies that state that their own developers must write every line of code.  Clarifying the meaning of open-source licenses will not necessarily change their minds.


答:
It depends on whether or not you need to do anything "interesting" with that additional, client-specific data.

In practice, it is unlikely that any processing will take place on custom fields, since you would have to provide that processing yourself, with some sort of plugin infrastructure or provide custom builds for each client, an arrangement which can quickly become unwieldy.

If there is no additional processing logic required, and custom fields can be provided to the client in a tabular format (as opposed to a columnar format), you can use an Entity-Attribute-Value design to provide custom field capability.  This allows the client to add the field definitions himself.

Further Reading

Entity-Attribute-Value model

Title: SQL - for some attributes specific to different clients' users, how to handle schema?

Body:
I have clients, each of whom have an app with a bunch of users.

Their user data could be pretty different, but there is also a lot of overlap. Ex: all their users have "gender" and "age" and plenty of other things, so it makes sense to have a standard user_table schema across all clients (with a column for each attribute).

But there is also user information specific to each client. Ex. one might have "relationship_status" for their users, which other clients do not have. While another has "height" for their users, which other clients do not have.

How to I design a schema that is appropriate for both of these cases at once?

One possibility is to somehow have a different schema for each client, but this seems like it could be unnecessary hassle. Another possibility is to put every column in the standard schema across all clients, but then the columns that are unique to a single client would just sit empty for all the other clients.


问:
How Do I Securely Edit a Database Entry Based On ID in an Admin System?
This is more of a conceptual question because the way that I am doing it would be secure enough for my purposes (educational). I created a simple admin panel that displays a stock picks database as inputs:

```<code>{% for pick in picks %}
        <tr data-post-id="{{i.id}}">
            <td class="symbol"><input type="text" value="{{pick.symbol}}"></td>
            <td class="buy_date"><input type="text" value="{{pick.buy_datetime}}"></td>
            <td class="buy_price"><input type="text" value="{{pick.buy_price}}"></td>
            <td class="sell_price"><input type="text" value="{{pick.sell_price}}"></td>
            <td class="quantity"><input type="text" value="{{pick.buy_quantity}}"></td>
            <td class="current_price"><input type="text" value="{{pick.current_price}}" disabled></td>
            <td class="save"><button>save</button></td>
        </tr>
{%endfor%}
</code>```

In the panel, you can edit the individual row and save it to the database through an ajax request based on the data-post-id. Then it dawned on me, if a malicious user was able to bypass the login system, could they edit any row in the table by changing the data-post-id in their browser? If so, what else can I do to limit what can be edited and make sure that only what is intended to be edited is edited?

答:
For casual protection, you can hash some identification fields (including the ID) and include the hash in the page.  When the page is posted, you hash the fields again, and compare them with the hash stored in the page.  Make sure it's a salted hash so that it's difficult for the attacker to recreate the hash algorithm and make their own fake hash.

For better protection, encrypt the ID before rendering it in the page, and decrypt it when the page is POSTed.

Further Reading

Prevent form tampering of hidden fields in Django

MVC Security Extensions

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
C# Subject Observer Architecture question
I'm making a C# application using the Subject Observer design pattern in a slightly different way.

I am passing the Provider Class, implementing IObservable (this has the OnNext() method that notifies all classes that subscribe to it), to the Observer Class constructor, implementing IObserver (this acts on the OnNext() method posted by the provider class).

That way every single Observer class has the capability of executing the OnNext() method notifying other classes of changes as well.

So a very simplistic look of my sample project goes like:

```<code>ProviderClass provider;
ObserverClass observer1;
ObserverClass observer2;
.......... observer3;
.......... observer'n';

main()
{
    provider = new ProviderClass();
    observer1 = new ObserverClass(provider);
    observer2 = new ObserverClass(provider);
    observer3 = new ObserverClass(provider);
    provider.subscribe(observer1);
    provider.subscribe(observer2);
    provider.subscribe(observer3);
    ............
    ............
    // arbitrary code happens here
    ............
    ............
    // later in code observer1,2,3 can each post OnNext() methods
    // that each other observer class will also catch since they all have
    //, so with some
    // filtering of objects being passed in each OnNext() method
    // I think this is a great way of passing data from one class to
    // another.
}

class ObserverClass : IObserver<Object>
{
    ProviderClass copyInstance;

    // Now the observer class can notify other classes using OnNext()
    public ObserverClass(Provider copy)
    {
        copyInstance = copy;
    }

    public virtual Override OnNext(....)
    {
        // perform specific action
    }

    public void notifyClasses(...)
    {
       copyInstance.OnNext(...);
    }
}
</code>```

Are there any drawbacks to modifying the Subject Observer design pattern this way?

答:
Are there any drawbacks to modifying the Subject Observer design pattern this way?

Well, yeah.

What I see is backwards, inside-out; an incorrect implementation

The observer (ObserverClass) should not be the notifier - the notifier is your ProviderClass. The notifier notifies, the observer observes.

Having the ObserverClass calling the providers methods makes no sense.

The code is setting up a circular reference, apparently. The provider calls the observer that in turn calls the provider's method, which in turn ...

If you want to "chain" observable the a class can implement both IObservable and IObserver.

Are there any drawbacks to modifying the Subject Observer design pattern this way?

Well, yeah.

What I see is backwards, inside-out; an incorrect implementation

The observer (ObserverClass) should not be the notifier - the notifier is your ProviderClass. The notifier notifies, the observer observes.

Having the ObserverClass calling the providers methods makes no sense.

The code is setting up a circular reference, apparently. The provider calls the observer that in turn calls the provider's method, which in turn ...

If you want to "chain" observable the a class can implement both IObservable and IObserver.

RE: 4/8/2015 comment

one class reads in files and searches for a keyword

I sense a single responsibility principle problem. Generally I see I/O functionality as a "single responsibility". Where to put the searching is dependent on the overall design.

the second class handles emailing the owner of the program ... [of the found keyword].

That sounds fine. I'm going to assume below that finding a keyword is the event trigger.

If both classes were instantiated in the main c# class then ...

You have a good place to coordinate the activities. The OO goodness here is that the Observer and the Observable do not have to really know about each other. Class types and event delegate signatures will ensure they can work together.

So "the main C# class" will:

Register an IObserver object's event handler on its behalf to the IObservable.

I suspect it may take these objects as constructor/method parameters.

Call to the I/O class to fetch the file.

Pass the file to the method/class that searches - this is the IObservable, if I'm guessing right about the intent.

Whatever does the search triggers the event when the keyword is found.

May un-register the event handler as well. Depends on object life cycle, design, intent, etc.

End RE: 4/8/2015 comment


问:
Vector API, naming for element-wise multiply
I'm helping develop a 3D Vector class, which has common operations such as:

v = v1.cross(v2)

v = v1 * v2 - infix multiply for dot product.

v = v1 + v2 - infix addition.

v = v1.slerp(v2) - spherical linear interpolation.

v.normalize() - make unit length.

These operations are very common for 3D Vector math classes (listed examples below).

Edit, we have classes for RGB Color, Rotations etc... so this question is specifically about 3D Vector's

My question is: Is there an API naming convention for element wise multiplication?

Apache-Commons-Math calls it ebeMultiply but this seems a bit ad-hoc and I didn't see the name used elsewhere.

Note:

While I rather not get into specifics here are some API's which are similar in scope to ours:

Unity3D, Apache Commons Math, Mahout, Armadillo, la4j

答:
Here are some ideas. Note: naming contests are not very suited to the StackExchange format, but the discussion of rationale behind naming choices could be suitable if useful principles can be summarized.

The question is meaningful in that it has a specific context: a 3D vector class.

While OP had not explained the precise use case of the class or library, one could easily imagine such a class could be useful for 3D geometry and 3D (RGB/YCbCr) colorspace.

However, if the library ever needs to extended to other usage, such as RGBA (transparency), 3D Perspective (projective) geometry, rotational mechanics, etc.,  it is foreseeable that a 3D vector class is insufficient on its own.

For example, a typical ColorMatrix implementation is a 5x5 matrix, with each column and row associated with: Red, Green, Blue, Alpha (opacity), and finally Constant-term. The needs for 3D perspective vector operations are similar: a 3D vector is padded with a fourth term named "scale" or "divisor", and operations are performed with 4x4 matrix.

Therefore, one will need to think about future extensibility of use cases, or to preclude them, when one considers naming issues.

Another fun-issue (or non-issue) is whether one would like to distinguish between 3D vectors of different physical meanings. The simplest case being a 3D vector in space representing (x, y, z), versus a 3D color vector representing (r, g, b). While this is all too easy to handle in most programming languages, you still have to choose a design with careful deliberation.

One more language-specific issue (before discussing the naming issue) is the operator overriding capabilities of that language. In particular, if the library will eventually support multiple languages, this requires careful naming.

In additional to the libraries mentioned above, one can also consider:

OpenCV Mat matrix expressions

Eigen array and matrix operations

Now, the naming.

Alternative names for multiplication, such as:

product, prod

mul

times

Words that indicate one-by-one processing as prefix/suffix:

each, elem, for,

Words that indicate data parallelism as prefix/suffix:

parfor, par, vec

Note: sometimes, a single letter prefix could be sufficient:

Intel SSE uses the letter "P" to indicate SIMD operations.

AMD NEON uses the letter "V" to indicate SIMD operations.

Combinations of such words:

elemMul, parMul, eachMul, mulEach, etc.


问:
Dynamic Code Evaluation in Java - Clever or Sloppy?
I am trying to create a flexible ACL framework in Java for my application.

Many ACL frameworks are built on a whitelist of rules, where a rule is in the form of owner:action:resource.  For example,

"JOHN can VIEW resource FOOBAR-1"

"MARY can VIEW resource FOOBAR-1"

"MARY can EDIT resource FOOBAR-1"

This is attractive because the rules can easily be serialized/persisted to a database.  But my application has complex business logic.  For example,

"All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized"

"All users in department 2, if the date is after 03/15/2016, can VIEW resource FOOBAR-2, else not authorized"

Upon first thought, it would be a nightmare to devise a database schema that could handle infinitely complex rules such as these.  Therefore, it seems as though I would need to "bake" them into the compiled application, evaluate them for each user, and then produce owner:action:resource rules as a result of the evaluation.  I want to avoid baking the logic into the compiled application.

So, I was thinking of representing a rule in the form of predicate:action:resource, where the predicate is a boolean expression that determines whether a user is allowed.  The predicate would be a string of a JavaScript expression that could be evaluated by Java's Rhino engine.  For example,

return user.getDept() == 1 && user.seniority > 5;

In doing so, the predicates could easily be persisted to the database.

Is this clever?  Is this sloppy?  Is this gimmicky?  Is this over-engineered?  Is this safe (apparently, Java can sandbox the Rhino engine).

答:
What you really want here is XACML. It pretty much gives you exactly what you want. You don't necessarily have to implement the full architecture with all the roles being completely separated... if you only have a single application, you can probably get away with integrating the PDP and PEP into your app with balana and the PIP is whatever your existing user database is.

Now, anywhere in your app you need to authorize something, you create a XACML request which has the user, the action, and the context, and the XACML engine will make the decision based on the XACML policy files you've written. These policy files could be kept in the database or on the filesystem, or wherever you want to keep the configuration. Axiomatics has a nice alternative to the XACML XML representation called ALFA that's a little easier to read than the raw XML, and an Eclipse plugin to generate XACML XML from ALFA policies.


答:
There are some things to be aware off: First, your company lawyers may get a fit if you use third party code without asking them. So you shouldn't use any third party code without telling your boss or manager and getting their consent. As you said, you are not a lawyer.

Second, a nasty one: If you find code on the internet, and it has some license, you don't know where it comes from. You don't know if the person who added the license actually had the right to do so.

Third, for GPL license and internal use: Things that are for internal use today may not stay for internal use. You might have written some really nice software for internal use, and your company might decide to make some money off it by selling it. And then you might have a problem.

Title: What kinds of Open-Source licenses are NOT OK to use internally in a corporation?

Body:
I have recently learned about several cool open source add-on tools and libraries for Microsoft Visual Studio. The tools just help you be more productive; the libraries would get linked into the corporate code base.

I have listed all these cool tools and libraries on a spreadsheet and I'm going to run down the type of license each one is under. So far, amongst my cool libraries, I see MIT, BSD, Apache License Version 2.0. However, there could be more in the future.

How can I find out (or better yet, can you just list) the popular licenses which are NOT compatible with internal corporate use (not to be distributed outside the company)? And for an extra thank you, can you say or point to an explanation. I'm not a lawyer and reading the fine print of these licenses gives me a headache.

I want to be prepared to explain why using the allowable licenses is OK.


问:
What are useful metrics for source code?
What are useful metrics to capture for source code?

How can metrics, like for example (Executable?) Lines of Code or Cyclomatic Complexity help with quality assurance or how are they beneficial in general for the software development process?

答:
The smaller the commits the better, usually. This is about SCM tools, not code per-se, but it's a very measurable metric. The smaller the commit the easier it is to see each change as an atomic unit; the easier it is to revert specific changes and pin-point when things broke.

As long as no commit breaks the build...

ContentLicense: CC BY-SA 2.5


问:
Why is XML type safe?
Why do they say that XML provides type safety and how is it expressed in the XML itself?

How is it different from JSON (for example) which (as I understand) is not type safe?

答:
Because of the XML Schema Definition (XSD).

With XML, you can have an additional file which describes the schema. It indicates, for example, that the element /a/b is an array and contains from 1 to 10 elements, or that the element /a/c is an integer. You can find an example of an XSD here.

Validation of a given XML file through an XSD is supported by many languages. For example, a .NET application may request an XML file from an untrusted source and check that it matches the XSD; then, it can save it to a Microsoft SQL Server database, which can in turn contains an XSD and do the check again (to ensure that any client which have access to the database complies).

XSD is not the only language.

If you've done web development, you certainly heard about Document Type Definition (DTD)—a markup language which defines the structure of XML and is used especially in validation of HTML-related content. While it cannot do all things XSD can, such as ensure that an element or an attribute contains an integer number, it can still perform a bunch of structure checks.

RELAX NG has a benefit of being relatively simple compared to other languages and can be written in a more compact form than XML.

Schematron is another “rule-based validation language for making assertions about the presence or absence of patterns in XML trees” (Wikipedia) and presents a slightly different approach, based on XPath assertions.

Similar initiatives for JSON are not that popular (especially, I believe, in Microsoft-centric corporate world). One of the reasons is that JSON is intended for situations where the data structure is rather basic (i.e. can be expressed as a tree, without the need for attributes, for instance) and don't necessarily need to be validated. An excellent example is a REST API used by a dynamically-typed language:

the client is very easy and fast to implement,

the API is trusted not to change,

the client can easily deal with specific leafs where validation is necessary (for instance check that /something/percentage is an actual number and is in 0..100 range).

Title: Why is XML type safe?


答:
XML can be type safe, since it it possible with XSD schemas to declare the data type of elements. A document validated against a XSD schema is guaranteed to conform to the expected types. But a XML format is not required to have a schema, so a document is not automatically type safe just by being XML.

There actually exist a schema language for JSON also, so type safe JSON is possible. But it is rarely used, so typically JSON is not type safe.

Title: Why is XML type safe?

Body:
Why do they say that XML provides type safety and how is it expressed in the XML itself?

How is it different from JSON (for example) which (as I understand) is not type safe?


问:
How come javascript, being a prototype based language, doesn't have an easy way to access the prototype?
May be this is a stupid question, but I'm kind of intrigued.

Being JavaScript a prototype based language, with its pseudo-class function constructors sort of half baked (remember JavaScript: The Good Parts ...) I wonder how is it possible that it didn't have, right from the start, some easy way to access the prototype of each object.

By easy way I mean something like object.prototype, or object._prototype (and not the dirty proto)

For what I know, the Object.getPrototypeOf(obj) was just added in late 2008, almost 13 years after JavaScript was launched.

I'm asking this because I always wondered if JavaScript was ever meant to be used as a pure prototype based language, I mean, without using any function to construct objects (in other words, never using the new operator).

答:
This is really a question about what went through Eich's mind when he designed the language, so it's only really him who can answer.

But if I should venture a guess, I would say the initial version of JavaScript was a quick-and-dirty prototype and he expected to be able to iron out inconsistencies and missing features in subsequent releases. But then it was quickly reverse-engineered with bug-for-bug compatibility by Microsoft and then standardized, which suddenly froze the language earlier than expected.

I'm pretty sure it was intended that instances should be created with 'new' like in Java, and it was more "an under the hood" implementation detail that inheritance happened through prototypes. The keywords 'extends' and 'implements' was reserved from the beginning, which hints that the language was expected to develop a more java-like syntax for inheritance. But until then, you had to munge with prototypes directly to use inheritance.

So the current situation is kind of half baked, and not the result of a deliberate design decision.


问:
forking but not exiting
It is normal for the child in a fork() to call exec() or _exit().

Are there any realistic scenarios where the child might return from the function that called fork() instead?

```<code>void foo() {
  pid_t pid = fork();
  if(pid == 0) {
     ...
     return; //<-- the child is going to unwind the cloned call stack
  }
  ...
</code>```

So what legitimate uses are there for a forked child returning?  Are there any standards that govern this?

答:
A trivial example of where the function calling fork is supposed to return in both the parent and the child is if the function calling fork is a simple wrapper function, and the caller of that function is the one that chooses what to do in the parent, and what in the child. A simple wrapper function might not make much sense for pure C, but POSIX C++ bindings could legitimately want to provide a posix::fork() function that simply calls the global fork() function, but can be declared in a header that does not pollute the global namespace.

caveman gave a good less trivial example in a comment on your question.

The relevant standards address this by not addressing it. The description of fork() is specified without any restrictions on returning from the function calling it, so implementations can't choose to disallow that.

It's like how the description of putchar doesn't say that implementations can't choose not to print 'a', but if an implementation did that, I'm pretty sure we'd be in perfect agreement that that's not what the standards say, that's not what the standards meant to say, and interpreting it like that is just silly.

Title: forking but not exiting


问:
What are common pitfalls of Cloud Development that you have run into?
I'm looking at beginning some work on a cloud based application and I'd be interested to hear of anybody's experiences of pitfalls they have run into particularly from a design/architectural standpoint when working with cloud platforms. Are there any expectations that might change significantly from regular web development practice? Things that you wish you had been aware of before you got started or that might have influenced your choice of platform had you been aware of them? I realise there are significant differences between the different options out there, but I feel there are significant enough similarities to warrant asking this as a general question.

Any experiences with particular platforms would also good- it would be interesting to see whether others have found similar things happening on other platforms too...

答:
Assume every node/machine/instance will fail often. Your architecture has to not only be tolerant of these failures but also expect that they will happen frequently. So your system shouldn't only survive such incidents, it should not even be bothered by them and should (ideally) heal itself when they happen.

It's my experience that particular cloud instances are usually much less reliable (in all parameters) than plain old servers. Their strength lies in their numbers, and not in any particular node. So make you system distributed and redundant at its core.


问:
What are the safety benefits of a type system?
In JavaScript: The Good Parts by Douglas Crockford, he mentions in his inheritance chapter,

The other benefit of classical inheritance is that it includes the specification of a system of types. This mostly frees the programmer from having to write explicit casting operations, which is a very good thing because when casting, the safety benefits of a type system are lost.

So first of all, what actually is safety? protection against data corruption, or hackers, or system malfunctions, etc.?

What are the safety benefits of a type system? What makes a type system different that allows it to provide these safety benefits?

答: One advantage not yet mentioned for a type system centers around the fact that many programs are read more than they are written, and in many cases a type system may allow a lot of information to be specified in a manner which is concise and can be easily digested by someone reading the code.  While parameter types don't take the place of descriptive comments, most people will find it faster to read: "int Distance;" or Distance As Int32 than to read "Distance must be a whole number +/- 2147483647"; passing fractions may yield inconsistent results."  Further, parameter types can help reduce the gap between what a particular implementation of an API happens to do, versus what callers are entitled to rely upon.  For example, if a particular Javascript implementation of an API uses its parameters in a way which would coerce any strings to numeric form, it may be unclear whether callers are allowed to rely upon such behavior, or if other implementations of the API might malfunction if given strings.  Having a method whose parameter is specified as Double would make it clear that any string values must be coerced by the caller before being passed; having a method with an overload that accepts Double and another that accepts String would make it somewhat clearer that callers holding strings would be allowed to pass them as such.


问:
Integration testing and database connection string in app.config
I am working on a project where SqlConnection is created via a static method, lets say it's DatabaseAccess.GetSqlConnection(). This method reads the .config file to get the connection string and creates a connection.

Is it ok to refactor the code to use an ISqlConnectionCreator (or ISqlConnectionFactory) responsible for creating the actual connections just for the sake of testing (as it seems more "by the book" for me) or go easy and just create a .config file in the test project containing test connection strings?

The second solution seems more error-prone and creates an indirect relation between tests and the tested classes.

I want to make sure there is a justification for the extra work of refactoring code to use the injected connection creator.

答:
From a pragmatic view I would recommend to use whatever works best, with the least maintenance effort.

In this specific situation, I would probably go with "option 3": separate the part which reads the connection string from the part which creates the actual connection into two different methods. So the connection string becomes an input parameter of method 2, and in your test code, you can omit the config evaluation and provide the test connection string any way you like, for example, as part of the hardcoded test data. As a result, you do neither need a test config file, nor an ISqlConnectionCreator.


答:
It looks like you are using your observer as both a publisher and a subscriber, while the Provider is only a publisher. Or is it both too? This seems a bit confused.

Maybe you should make some kind of Bus or Queue that you can both Publish and Subscribe to. There are so many complexities in messaging that you really should make a distinct component be responsible for handling only that.

Title: C# Subject Observer Architecture question

Body:
I'm making a C# application using the Subject Observer design pattern in a slightly different way.

I am passing the Provider Class, implementing IObservable (this has the OnNext() method that notifies all classes that subscribe to it), to the Observer Class constructor, implementing IObserver (this acts on the OnNext() method posted by the provider class).

That way every single Observer class has the capability of executing the OnNext() method notifying other classes of changes as well.

So a very simplistic look of my sample project goes like:

```<code>ProviderClass provider;
ObserverClass observer1;
ObserverClass observer2;
.......... observer3;
.......... observer'n';

main()
{
    provider = new ProviderClass();
    observer1 = new ObserverClass(provider);
    observer2 = new ObserverClass(provider);
    observer3 = new ObserverClass(provider);
    provider.subscribe(observer1);
    provider.subscribe(observer2);
    provider.subscribe(observer3);
    ............
    ............
    // arbitrary code happens here
    ............
    ............
    // later in code observer1,2,3 can each post OnNext() methods
    // that each other observer class will also catch since they all have
    //, so with some
    // filtering of objects being passed in each OnNext() method
    // I think this is a great way of passing data from one class to
    // another.
}

class ObserverClass : IObserver<Object>
{
    ProviderClass copyInstance;

    // Now the observer class can notify other classes using OnNext()
    public ObserverClass(Provider copy)
    {
        copyInstance = copy;
    }

    public virtual Override OnNext(....)
    {
        // perform specific action
    }

    public void notifyClasses(...)
    {
       copyInstance.OnNext(...);
    }
}
</code>```

Are there any drawbacks to modifying the Subject Observer design pattern this way?


答:
If you intend to use the interface for easier testing, then it should expose all the logic you wish to test on the Car business object. That means every operation that relates to the Car and not the technical implementation.

In your example, I would include all those methods in the ICar.

I would not leave out some methods even if only some cars have them. You should put those in a separate interface, or use inheritance, depending on the situation.

Title: When to make a method part of an interface or a concrete implementation?

Body:
I create an interface for database access to a MySQL database.  Currently, this is the only way to access day, but to make it easier to test and in the event that the data access might change, I used an interface.

However, now I am faced with the dilemma of which methods I should put on the interface and which methods I should put on the concrete implementation" directly.  Is there a rule of thumb for this?

I will give an example below where I have some CRUD operations for a ICar interface, but then some other utility functions that are just on the concrete implementation.  Should these be on the interface as well?  I wouldn't want a user to have to implement every method if they didn't need to?

```<code>interface ICar {
   Car GetCar(int id);
   void DeleteCar(int id);
   void InsertCar(Car car)
   Car UpdateCar(Car car);
}

class Car : ICar {

  Car GetCar(int id) {}

  void DeleteCar(int id) {}

  void InsertCar(Car car) {}

  Car UpdateCar(Car car) {}

  // methods not on interface, but should they be

  public string GetCarVIN(Car car) {}

  public string GetCarColor(Car car) {}

  public string GetCarMake(Car car) {}

  public string GetCarModel(Car car) {}

  public string GetCarOwner(Car car) {}
}
</code>```


答:
The eight fallacies of distributed computing:

"Essentially everyone, when they first build a distributed application, makes the following eight assumptions. All prove to be false in the long run and all cause big trouble and painful learning experiences.

The network is reliable

Latency is zero

Bandwidth is infinite

The network is secure

Topology doesn't change

There is one administrator

Transport cost is zero

The network is homogeneous

For more details, read the article by Arnon Rotem-Gal-Oz
"

http://nighthacks.com/roller/jag/resource/Fallacies.html

Title: What are common pitfalls of Cloud Development that you have run into?

Body:
I'm looking at beginning some work on a cloud based application and I'd be interested to hear of anybody's experiences of pitfalls they have run into particularly from a design/architectural standpoint when working with cloud platforms. Are there any expectations that might change significantly from regular web development practice? Things that you wish you had been aware of before you got started or that might have influenced your choice of platform had you been aware of them? I realise there are significant differences between the different options out there, but I feel there are significant enough similarities to warrant asking this as a general question.

Any experiences with particular platforms would also good- it would be interesting to see whether others have found similar things happening on other platforms too...


问:
Should I modify an algorithm I coded for my employer if I remember the code perfectly and want to reuse?
My employer asked me to code a simple algorithm from a general description published by someone on the Internet (no code/pseudocode, just plain words and pictures). So to clarify, it's not my employer's invention. I guess the algorithmic idea isn't patented either.

Now let's imagine I want to use that algorithm for my own purposes. The thing is that my way of thinking is still mine, I remember my code quite well down to the variable names, so if I'll rewrite it from scratch, chances are that it will be almost identical to my work version.

I don't plan to publish this bit of code but use in my project. Should I deliberately introduce changes to my version just in case, even if they're unnecessary and impact code clarity?

答:
Your code will be identifiable

Your coding style is going to be a little bit unique, distinct and recognizable no matter what you're programming, whether you're doing it for your employer now, or for yourself or a different employer later. So don't kid yourself that you can switch up a few variable names and make it look like different code. But that probably isn't the issue.

IP Ownership

If your employer pulled a description of the algorithm off the Internet, then your employer obviously doesn't own any IP in the idea, but they still own your work product if it is work for hire. Your work product is the digital copy of the specific code you produced for them, or printouts of the same.

They probably can't prohibit you from writing your own independent implementation of an algorithm where the original IP doesn't even belong to them. In fact, are you 100% certain your employer had a right to the IP themselves? ;-)

Work For Hire

If you are a W-2 employee you are by definition producing "work for hire" in which you have relinquished rights and ownership of your work product to your employer. I don't know who could guarantee that a good IP attorney couldn't make the case that a re-implementation from memory is materially the same thing as the original tangible work product.

If you're an independent contractor (1099), then this is going to depend on your contract. If your contract says it's work for hire, your employer owns the work product. If not, then your employer owns a perpetual license to use the work you produced, but you retain the copyright yourself, in which case you can do whatever suits you including selling the code you produced either on its own or as a part of your own product.

CAVEAT: I am not an IP attorney. But the law isn't all that obtuse on the subject.

Statutory Employee

Be aware that you could potentially be declared an employee retroactively, and your work declared to be work for hire if the employer controls your schedule, controls where you are able to do the work, controls the equipment you use, controls whether you can hire assistants or have to do all the work yourself, if the relationship is very long-term, if the employer pays you benefits that are normally considered to be regular full-time employee benefits, and so on.

Ethics

Is it such a generic algorithm that it can be used in totally different, non-competing applications? Or are you privately developing a product (of which the code in question is a component) which would compete with your employer's product? If so, quit your job with your employer now and eliminate your conflict of interest. Developing a competing product while working for your employer is ethically slippery, and might be legally actionable.

If your product is something unrelated, I probably wouldn't get worked up about it, unless you have some kind of restrictive employment agreement in place.

Employment Agreements

Did you sign a highly restrictive employment agreement, NDA, IP agreement or non-compete? That's going to vary by employer. In a job for an AT&T subsidiary once long ago I basically had to sign an agreement that said every stray thought I had any time of the day or night whether I was awake or dreaming, at the office, at home or on vacation, was their property as long as I was their employee and for something like six months after my employment with them ended, that if I developed a product even years after leaving them and they could prove that I had the idea for the product while in their employ that they would own that product and I would assist them in their legal effort to secure that ownership. There wasn't any provision that said the idea would only belong to them if it pertained to a line of business they were in at the time I had the idea. The agreement also said that I wouldn't take a job for anybody doing any of the same things they did for at least two years after termination of my employment.

The two-year non-compete was about keeping my knowledge, insights and experience obtained while working for them from being useful for anybody else and would have applied to working for myself, as well. Of course as a lifetime progresses, people acquire knowledge and insights from all kinds of sources that they take to their employer, rather than obtaining from their employer, especially in the Internet age. So I think proving the true genesis of any idea or technique can be genuinely trickier now than, say, 25 or 30 years ago.

In retrospect, I feel that kind of agreement is somewhat less than 100% ethical or fair, and I feel I was too young and dumb to realize they weren't paying me anywhere remotely close enough for a no-stakes wage-only position to deserve to have me sign an agreement like that. But it was what it was, I signed it, it was legal and I needed the work and experience and in the end I'm pretty sure my employer and I benefited each other mutually.

But the work for hire statutes apply regardless of the specific employment agreement(s) you sign.

Burning Bridges, Poking Bears

In general, intact bridges produce more opportunities than burned ones, and life is long and varied and you never know when you're going to encounter a potential opportunity with the same old employer, or with one of their friends or associates. If you go around poking bears, sooner or later one of 'em is going to bite you.

Do you think you might be able to approach your employer and just ask if they'd be okay with you rewriting this bit of code (not just copying what you wrote for them), for your own unrelated purposes, on your own time, at your own place, using your own equipment?


问:
What happens when one reaches their framework's maximum requests per second?
I've been dabbling in code for many years now but it's always been personal projects. I don't have experience with much traffic. I was recently reading through a "Hello, World." tutorial for Dropwizard and at the bottom it states "Well, congratulations. You’ve got a Hello World application ready for production (except for the lack of tests) that’s capable of doing 30,000-50,000 requests per second."

Although what I can only imagine as being a good problem to have, what do you have to start doing at that point? If my application was built upon Dropwizard, would I have to start migrating to something different, or is that where deploying to multiple "nodes" and load balancing comes in?

答:
That's generally where horizontal scalability (distributed computing/multiple nodes and load balancing) comes into play. Every system is going to have some kind of upper limit on vertical scalability.

One critical key to horizontal scalability is state management. You want to design your software so that individual sessions don't require affinity to a specific node. The less work the load balancer has to do to keep utilization even across the nodes, the better. And if you're putting the burden of state management onto a back-end server (maybe a database), you need to be aware of that resource becoming a bottleneck despite your load balancer. So perhaps you look into database federation or table sharding (best to use a framework instead of manual sharding, in my opinion. For instance, how do you decide the criteria for key splitting? How do you adjust that when you discover that your assumptions about the key distribution were wrong?)


问:
When to make a method part of an interface or a concrete implementation?
I create an interface for database access to a MySQL database.  Currently, this is the only way to access day, but to make it easier to test and in the event that the data access might change, I used an interface.

However, now I am faced with the dilemma of which methods I should put on the interface and which methods I should put on the concrete implementation" directly.  Is there a rule of thumb for this?

I will give an example below where I have some CRUD operations for a ICar interface, but then some other utility functions that are just on the concrete implementation.  Should these be on the interface as well?  I wouldn't want a user to have to implement every method if they didn't need to?

```<code>interface ICar {
   Car GetCar(int id);
   void DeleteCar(int id);
   void InsertCar(Car car)
   Car UpdateCar(Car car);
}

class Car : ICar {

  Car GetCar(int id) {}

  void DeleteCar(int id) {}

  void InsertCar(Car car) {}

  Car UpdateCar(Car car) {}

  // methods not on interface, but should they be

  public string GetCarVIN(Car car) {}

  public string GetCarColor(Car car) {}

  public string GetCarMake(Car car) {}

  public string GetCarModel(Car car) {}

  public string GetCarOwner(Car car) {}
}
</code>```

答:
OP is having this confusion because of poor naming.

The reason OP asks this question is because OP has a confusion between the Repository Pattern and general object-oriented design.

The repository object sits between the OOP design - say, a Car class, and the database.

The "repository-object" relation shall not be confused with the "interface-implementation" relation or the "class-object" / "static-instance" relations.

A Car object provides access to the properties that a car (in real life) will usually have (named VIN, Color, Make, Model and Owner in the code example).

On the contrary, the repository object looks like a CarCollection in the abstract sense. The repository object is where CRUD operation belongs to.

To fix this issue, CRUD methods should exist on a CarRepository class (and optionally implementing an ICarRepository interface), and then Car-related methods should exist on a Car object and/or a ICar interface.

In C#, you can both keep the interfaces clean and still give the convenience to your users by using Extension methods.

Keep in mind that if the conceptual mix-up of repository object with data object is enough to give OP headaches, users of such conceptual mix-up is going to get the same kind of headaches, unless the users are being forewarned about it.

```<code>public interface ICarRepository
{
    ICar GetCar(int carId);

    // ... other CRUD and query methods,
    // ... but NO car-properties here.
}

public interface ICar
{
    string Owner { get; }
    string VIN { get; }

    // ... other car-properties here.
}

namespace ExtensionMethods
{
    public static class CarExtensions
    {
        public static string GetCarOwnerFromId(this ICarRepository carRepo, int carId)
        {
            return carRepo.GetCar(carId).Owner;
        }

        public static string GetCarVINFromId(this ICarRepository carRepo, int carId)
        {
            return carRepo.GetCar(carId).VIN;
        }
    }
}
</code>```

Body:
OP is having this confusion because of poor naming.

The reason OP asks this question is because OP has a confusion between the Repository Pattern and general object-oriented design.

The repository object sits between the OOP design - say, a Car class, and the database.

The "repository-object" relation shall not be confused with the "interface-implementation" relation or the "class-object" / "static-instance" relations.

A Car object provides access to the properties that a car (in real life) will usually have (named VIN, Color, Make, Model and Owner in the code example).

On the contrary, the repository object looks like a CarCollection in the abstract sense. The repository object is where CRUD operation belongs to.

To fix this issue, CRUD methods should exist on a CarRepository class (and optionally implementing an ICarRepository interface), and then Car-related methods should exist on a Car object and/or a ICar interface.

In C#, you can both keep the interfaces clean and still give the convenience to your users by using Extension methods.

Keep in mind that if the conceptual mix-up of repository object with data object is enough to give OP headaches, users of such conceptual mix-up is going to get the same kind of headaches, unless the users are being forewarned about it.

public interface ICarRepository
{
    ICar GetCar(int carId);

    // ... other CRUD and query methods,
    // ... but NO car-properties here.
}

public interface ICar
{
    string Owner { get; }
    string VIN { get; }

    // ... other car-properties here.
}

namespace ExtensionMethods
{
    public static class CarExtensions
    {
        public static string GetCarOwnerFromId(this ICarRepository carRepo, int carId)
        {
            return carRepo.GetCar(carId).Owner;
        }

        public static string GetCarVINFromId(this ICarRepository carRepo, int carId)
        {
            return carRepo.GetCar(carId).VIN;
        }
    }
}


答:
Learn from the Chaos Monkey.

We’ve sometimes referred to the Netflix software architecture in AWS as our Rambo Architecture. Each system has to be able to succeed, no matter what, even all on its own. We’re designing each distributed system to expect and tolerate failure from other systems on which it depends.

One of the first systems our engineers built in AWS is called the Chaos Monkey. The Chaos Monkey’s job is to randomly kill instances and services within our architecture. If we aren’t constantly testing our ability to succeed despite failure, then it isn’t likely to work when it matters most – in the event of an unexpected outage.


问:
Best solution for future maintenance of a website with hardcoded ids, custom CMS using bad database design
Recently I was put into a position of a tech-lead on a very interesting project that I have been partially working for two years. This project carries a lot of legacy stuff with it even though we try to strip it down.

I am looking and researching a solution for my scenario:

the website has lots of hard-coded IDs (even though they are extracted to one single place).

it has bad database design that we can't touch (because of custom CMS) and it prevents us from doing simple select statements that would get us the exact data that we need (that is why we have to hard-code IDs)

it is using custom CMS that is maintained by different company

because of hard-coded IDs (that often change) we have to do frequent releases (which raises a risk and brings extra cost for the customer).

The main concern that I have now is to prevent these releases because of hard-coded IDs.

The most sensible approach to this situation for now I came up with would be:

Move the IDs to new database and create a sensible structure there. Create basically a middle layer between the website and database. Create a new website for the new database for a client to manage. Which would essentially create another custom CMS which is again not ideal but better than frequent releases.

OR

Start using a commercial new CMS for IDs mentioned above and slowly migrate the whole website to a new proper CMS.

Have you ever experienced a project like this? What would be your best approach for this?

答:
It's been six months since I asked this question and the result is that we did kind of compromise between the custom CMS and our web application.
We introduced a few new fields in the CMS that would enable us to query the database in more reliable and flexible manner. After that we introduced a few new queries that help us getting the data dynamically. This seems to be as a good move as we got rid of all the hard-coded IDs and our code base shrinked as well so it's much easier to maintain.</p>


答:
Source code metrics for quality assurance aim at two objectives:

writing code with less bugs inside

writing code for easy maintenance

Both lead to writing code as simple as possible. This means:

short units of code (functions, methods)

few elements in each unit (arguments, local variables, statements, paths)

and many other criteria more or less complex (see Software metric in Wikipedia).

Title: What are useful metrics for source code?

Body:
What are useful metrics to capture for source code?

How can metrics, like for example (Executable?) Lines of Code or Cyclomatic Complexity help with quality assurance or how are they beneficial in general for the software development process?


问:
Strategy for creating a websocket relay?
I own a Raspberry Pi and would like to use it as some sort of websocket relay, so that all people who visit a specific webpage would be able to communicate with each other. The key thing about this is that I want to define my communication protocol in Javascript on the client side. (IE: The messages that clients send to each other)

Are there any strategies for accomplishing this? Is such a relay already available via some sort of Apache extension (or similar)? Knowing C#, my first thought is to develop a C# service application that would run on top of Mono on the Pi. Does that sound like a good idea?

In my specific case, I'm looking to create a HTML5 multiplayer game. I know there are blindingly obvious cheating issues with my proposed implementation, but please keep in mind that this is an experiment, not something serious.

答: See this tutorial on a NodeJS/JavaScript client chat application to give yourself a starting point. I don't know if there is a FOSS chat application like this one written in C#, but if you are most comfortable in C# it might be worth doing some research to see if you can find something comparable to this Node solution. </p>


问:
Agile Use Of Dedicated Teams
When reading the Agile Manifesto, they don't mention anything about dedicated teams. However on some websites (example: this article on agile teams) they claim it's necessary to have a dedicated team to work agile. I understand it's a critical success factor, however, is having a dedicated team obligatory to work agile?</p>

答:
If you don't have dedicated teams, many agile tools will not work. Burndown charts, story points, the foundation of estimating and planning is pretty much worthless when you have a high or very high turnover rate in your "team". </p>

<p>Being a team and working as a team is a core principle of at least SCRUM (I guess you could have kanban with constantly shifting members). SCRUM gets better iteratively because the team will know each other better and can make better estimates based on previous experience. If you don't have a dedicated team, it's like starting SCRUM all over any time your team changes completely. </p>

Title: Agile Use Of Dedicated Teams

Body:
If you don't have dedicated teams, many agile tools will not work. Burndown charts, story points, the foundation of estimating and planning is pretty much worthless when you have a high or very high turnover rate in your "team".

Being a team and working as a team is a core principle of at least SCRUM (I guess you could have kanban with constantly shifting members). SCRUM gets better iteratively because the team will know each other better and can make better estimates based on previous experience. If you don't have a dedicated team, it's like starting SCRUM all over any time your team changes completely.


答:
Note that in most articles, dedication means that the person is committed to the success of the project, not that the team is dedicated in a management sense.

Example from the article you linked to, emphasis mine:

[...] are dedicated to continuously improving their ability to deliver software

Another example, from Successful Teams Are Small And Dedicated, emphasis mine:

And it gets worse: dedicated team members aren’t so understanding of these “fence straddlers”. Frustration at their lack of commitment quickly escalates into open conflict and, when no remedy is found, casting that person out of the team.

The dedication to the success of the team is indeed a critical success factor. If some team members don't feel that they should do whatever they need for the success of the project, they are not good candidates for agile teams.

For instance, one of the behaviors expected from each member in an agile team is to do tasks which are broader than the core skills of the person: a Python developer should be able to go and fix an SQL query if needed, and a JavaScript developer can explore and fix Python code if needed.

In this situation, a non-dedicated person will simply expect others to do their jobs. A Python developer will blame the DBA for being late, and a JavaScript developer will blame server-side developers. With this sort of relations between team mates, chances are that any form of agile will fail.

The management-type dedication, on the other hand, may be crucial or not, depending on the circumstances. If some members don't know how much they will spend working on the project for the next sprint, it may become difficult to manage the project.

From the article you linked to:

Each team member is fully dedicated to the team and works intensely during a responsible workweek.

On the other hand, nothing forces a person to work on a single project. Some people may have very specific and very important skills, and several projects at a time can benefit from those skills. For instance, someone who is very skillful at security or optimization may not necessarily be needed full-time on a project.

Title: Agile Use Of Dedicated Teams

Body: When reading the Agile Manifesto, they don't mention anything about dedicated teams. However on some websites (example: this article on agile teams) they claim it's necessary to have a dedicated team to work agile. I understand it's a critical success factor, however, is having a dedicated team obligatory to work agile?</p>


答:
In computer science, type safety is the extent to which a programming language discourages or prevents type errors.

Type safety is not an absolute attribute. It is not boolean. Languages (and XML and JSON are languages) allow and prevent different kinds of errors and mistakes. For example you can misname elements. But you cannot skip required syntactic elements such as closing tags and braces.

Plain XML and JSON are pretty much equally type-safe (or type-unsafe). A valid XML/JSON string has a certain syntactic and semantic structure but this almost never is enough for an application to work with it. Applications don't just any a structure but a specific one.

XML shines with XML Schema Definition (XSD) which is a flexible and powerful way to validate a given XML document against a schema. This provides a lot of type safety under the definition given above.

Title: Why is XML type safe?


问:
asp.net tracing custom implementation
I want to do event tracing in asp.net.
That is whenever any method is called, i want to log some method specific details into a text file like method name, return value e.t.c

But, as requests will come from multiple clients, writing to a single file will lead to file getting locked and contention problems. can anyone pl suggest some easy way of doing this.

I am trying to use a custom tracelistener from system.diagnostics.tracing, but not sure how to handle problems due to multi-threading issues that i have mentioned above.

Any suggestion would be greatly helpful. thanks.

答:
Don't reinvent the wheel.

.NET Framework already has logging that you can easily use in your application.

The logging framework will handle the multithreading for you (and TraceSource is thread-safe according the documentation). Under the hood, when the log file cannot be written (which is quite rare, since TraceSource uses a global lock internally, and doesn't necessarily flush every message to the file immediately), it will create another file with a GUID in its name (which ensures that the name is unique). For instance, if the main file is called app.log, it will create a file similar to app-f24742d6-ec9c-44e6-8ba5-c0ef1a70dc00.log.

Note that the files containing the logs are created automatically. The name of the file is configured through the configuration file (illustration in point 1, scroll the code to the right). Also, you are not limited to log files; you can for instance configure the application to log important messages to Windows Events.

The thread-safety of TraceSource means that you can make it static and call it from different instances (otherwise, you would be forced to create a TraceSource at instance level, which doesn't make much sense). This doesn't mean that there should be only one TraceSource in your application; the common pattern is to have one static TraceSource for every class which uses logging: this reduces coupling between classes, given that multiple TraceSources use the same application configuration. How to use TraceSource across classes provides an example of such pattern.

You may also want to look at how third-party log libraries solve the same problem. log4net is a popular alternative to .NET Framework's logging library, and:

is thread-safe [...] - the framework manages everything for you.

Source: Log4Net FileAppender not thread safe?

Also, if you're interested in logging every method, you may search for AOP. One of the practical uses of AOP is to be able to trace every call to every method, without having to do the tedious task of including code related to logging in the methods themselves.

Title: asp.net tracing custom implementation


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
As for magic numbers: they are bad if they are used in different places and changing it requires you to syncrhonise it in several places. But one number in one place isn't any worse than having one constant to denote one number that is still used in one place.

Furthermore, constants might not have much place in your application. In many database apps, those things should be stored in the database as per app or per user settings. And to complete their implementation they involve this setting and a place in the ui and a note in the end user documentation... all of which is kind-a overengineering and a waste of resources if everyone is perfectly happy when the number is 5 (and 5 it is.)

I think you can leave numbers and strings in place until there is a need to use this number outside that place. Then it is time to refactor things to a more flexible design.

As for strings... I know the arguments, but this is one more place there is no point in doing a one-string-to-one-constant conversion. Especially if the strings in place are coming from a constant implementation anyway (for example, imports that are generated from an outside application, and have a status-string that is short and recognisable, just like 'Overdue'.) There just isn't much point in converting the 'Overdue' to STATUS_OVERDUE when it is used in only one place anyway.

I am very much for not adding complexity if it doens't actually create needed benefits on flexibility, reuse or error checking. When you need the flexibility, code it right (the refactor thingy). But if it isn't needed...