问:
Why is .NET VM based?
Java has been designed to run on a virtual machine to allow portability for programs.

However .NET has been designed from the start specifically for Windows.

Than what is the reason for .NET applications being compiled to bytecode for the CLR?

Was it simply to copy Java? Or is there a technical advantage to just compiling natively?

答:
Compiling to some bytecode is an old tradition. UCSD P-code existed in 1978, and had many precursors. Today, LLVM can be seen as a bytecode, targetted by Clang/LLVM ahead-of-time compiler suite and GCCJIT can be viewed as a JIT related to GCC (with GIMPLE sort-of being some internal bytecode).

(hence, bytecode, JIT, ... has quite fuzzy meanings today; JIT's broadest sense is compilation inside the process running the compiled code.)

The JVM bytecode was initially implemented as interpreter. But Java become popular enough to get JIT based JVMs (and Sun invested a lot in JIT technology, so this helped Java to become successful).

And JIT existed long time ago (in the early 1980s, e.g. in Lisp machines, and even in 1960 on the CAB 500 computer and others), before even the name was used. Many Common Lisp or Smalltalk implementations had JIT compilers (and today, SBCL is fully JIT-ing).

In my understanding, Microsoft designed the CLR bytecode to be JIT compiled (hence got different tradeoffs in its bytecode than the JVM). And it has recently published its implementation as open-source software and ported it to Linux (before that, Mono existed on Linux).

A bytecode is often more compact than native binary executables, it can be made portable to several architectures (e.g. x86 32 bits and x86-64 and also ARM 32 bits, ARM/Aarch64, ...) and might be designed to avoid (or at least soften) dependency hells.

A big advantage of JIT compilation is that the VM can recompile some parts of the bytecode based upon dynamic contextual information (e.g. profiling, call stack introspection, ...) some code. Some JIT-ing infrastructures like libjit, asmjit, LLVM, GCCJIT, ... don't do that (however, the implementation using them could do that by repeated use of the JIT-ing infrastructure), but most industrial JVM or CLR implementations do it (and some people call JIT only that lazy on-demand dynamic compilation; for me JIT is just a buzzword for dynamic compilation at runtime).  This is difficult or impossible with AOT compilation (at least, requires LTO), and is impossible if you want to do profile-guided optimization dynamically at runtime (as most JVM or CLR JIT implementations are rumored doing). Also, a bytecode VM don't need to JIT-compile all the bytecode, but only the most used parts (as HotSpot does) and keep interpreting the rarely used cold code.

Also JIT implementations can cooperate much more (and better...) with sophisticated garbage collectors.

PS. I know nothing about Windows. I never used it. I'm using Linux since 1994 and Unix since 1987.

Title: Why is .NET VM based?


问:
What is the best design principle to add behavior in future to your API?
I'm designing an API. And, this API will be used by client.

Currently I've two behaviors in a class definition. To illustrate the scenario, sample implementation looks like the following-

```<code>public class Session {

    // instance field declaration goes here

    void connect() {
        // method definition goes here
    }

    void submitJob() {
        // method definition goes here
    }
}
</code>```

I want to add more behaviors to this class definition in future to offer more functionality. And, I don't want the client code to change (i.e. My client will keep instantiating this single class and invoke behaviors as per their need.) But, I don't want to modify this class definition. Is there any design pattern and/or principle that can be followed to add behaviors to achieve the goal?

Note: I do not intend to add behaviors at runtime.

Appreciate any explanation and/or guides.

答:
Code against an interface

Session isn't inheriting the 2 methods from an interface. Is it for the sake of brievity ? If not, you should always declare an API with an interface.

```<code>public interface Session {
    void connect();
    void submitJob();
}

public class HttpSession implements Session {
    @Override
    public void connect(){

    }

    @Override
    public void submitJob() {

    }
}
</code>```

Evolution of your API

The fact that you methods don't take any parameters could block you in the future. Explanation:

```<code>Session session = SessionFactory.create();
session.connect();
</code>```

The code above could be an exemple of the current use of you API. Maybe in the future you will see the need to accept a parameter token for connect. In this case you're screwed because you need to change your interface to

```<code>public interface Session {
    void connect(String token);
    void submitJob();
}
</code>```

What if you need to add another parameter ? and change your interface to

```<code>public interface Session {
    void connect(String token, String username);
    void submitJob();
}
</code>```

It seems you are screwed again and again...

To resolve that, one practice I already saw in API design (disclaimer: I don't know if it's a good practice or not) is that you add an object parameter to the method.

```<code>public interface Session {
    void connect(ConnectParameters params);
    void submitJob();
}

public final class ConnectParameters {
    private final String token;
    private final String username;
    //TODO: add future parameters here

    ...
}
</code>```

With this solution, you have a guarantee that the signature won't evolve and break your API.

ContentLicense: CC BY-SA 3.0

Body:
Code against an interface

Session isn't inheriting the 2 methods from an interface. Is it for the sake of brievity ? If not, you should always declare an API with an interface.

public interface Session {
    void connect();
    void submitJob();
}

public class HttpSession implements Session {
    @Override
    public void connect(){

    }

    @Override
    public void submitJob() {

    }
}

Evolution of your API

The fact that you methods don't take any parameters could block you in the future. Explanation:

Session session = SessionFactory.create();
session.connect();

The code above could be an exemple of the current use of you API. Maybe in the future you will see the need to accept a parameter token for connect. In this case you're screwed because you need to change your interface to

public interface Session {
    void connect(String token);
    void submitJob();
}

What if you need to add another parameter ? and change your interface to

public interface Session {
    void connect(String token, String username);
    void submitJob();
}

It seems you are screwed again and again...

To resolve that, one practice I already saw in API design (disclaimer: I don't know if it's a good practice or not) is that you add an object parameter to the method.

public interface Session {
    void connect(ConnectParameters params);
    void submitJob();
}

public final class ConnectParameters {
    private final String token;
    private final String username;
    //TODO: add future parameters here

    ...
}

With this solution, you have a guarantee that the signature won't evolve and break your API.


答: Windows is not a single, homogenous platform. When the first version of the clr was released, it targeted not only the traditional windows 98 family of systems (which only ran on x86) but also windows nt 4 (x86, ppc, alpha, mips). Support for windows ce (which ran on x86, sh, arm, mips and ppc) was added in version 1.1, while ia64 ("itanium") and x86-64 targets on nt were added in version 2. It is quite likely that the developers knew that most or all of these platforms would need to be supported when the project began. In fact, it seems probable that the fact that ISVs weren't keen to support this many hardware platforms and tended to only release x86 versions of applications figured in microsoft's decision to go ahead with developing the system.</p>

Title: Why is .NET VM based?

Body:
Java has been designed to run on a virtual machine to allow portability for programs.

However .NET has been designed from the start specifically for Windows.

Than what is the reason for .NET applications being compiled to bytecode for the CLR?

Was it simply to copy Java? Or is there a technical advantage to just compiling natively?


问:
Upgrade and downgrade customers subscription
I have been stuck at a requirement for way too long too handle it :(.

Our company is having increased number of customers who wants to upgrade or downgrade their  subscription. For now, the subscription-customer relation is at follows:

Every Customer has its own Combo, like the following:

Every Combo is bind to several packages:

When a customer wanted to upgrade his combo, the IT department had to add manually the upgrading package with the start and end date specifications. Since this was a rare request at a time, nothing has been thought for an automatic solution to it. Now, in Upgrade, I have managed to add another Package which has the missing products. The problem is on Downgrade. My initial thought was to edit the enddate field of the package that has to be cancelled, in order that the application would not read it no more. But, maybe is not a good idea to overwrite the existing data, because in the future, it will be impossible to understand if the enddate field was changed by mistake or on purpose.
Since tha application delivers the product via the package, reading its enddate, how can i manage to cancel the required package without overwritting it?

EDIT:

If the customer needs to renew the services, there are two steps taken:

In the first image is added a new row with the combo and saledate specification

In the second image,

a. if the new combo is equal to the old one, it changes the end-date for each package according to the duration

b. if the new combo is different from the old one, in that case, or the new packages are added, and the old ones do not change (This is the case when the new and old combo have no packages in common), or

c. the packages are edited as mentioned in point a) except one package, which is not included in the new combo . This is the case when only one package does not renew its end-date ( This is the case eligible for an upgrade)

Or should I go on with the "Edit Field" idea?

UPDATE:
As one of the possible solutions, I was thinking about adding a database field, which would activate or deactivate one or more package. Meanwhile, I have created a table which saves the pair of combos and the packages that differs them. I don't know if this is a good approach, in order to keep track of everything that happens in the user's experience

答:
As you are already updating the enddate field selectively for a renewal, it should not be a problem to also update the enddate field in case of a downgrade.

To be able to answer customer questions/complaints after a downgrade, there are several possibilities.

One of the easiest would be to add a column cancellation to the table with packages, recording the date that the package was cancelled.

Another mechanism, that gives you full details when something was changed, is to setup an audit system for those tables. This may even already exist, but if it doesn't, an audit system in its simplest form is a table that you automatically add a row to when something gets changed in another table to record what got changed and when. The only changes made to an audit table are inserts.

If, as indicated, there are organizational issues with updating the end date for a downgrade, the easiest solution is to add a 'cancellation' column with the cancellation date and to update the logic that checks if a package is purchased by a customer to take the cancellation column into account as well.


问:
Algorithm for predicting outcome based on parameters
I've never done anything with statistics, so I'm unsure of how to start with this problem that I need to solve for some software that I'm working on.

Basically, there are three parameters

An integer parameter (A) that can be a range of (for the sake of argument) 1-10

A Boolean parameter (B) that if present weights the value of A.

An integer parameter (C) that can be a range of 1-100.

There is one outcome: An integer (D) that can be of the range -1, 0, 1.

For each value of C, there will be one value of A, B, and D. C is a preexisting condition. A, and B are parameters. D is the outcome, which may be subjective.

```<code>+---+----+---+----+
| C | A  | B | D  |
+---+----+---+----+
| 1 |  3 | 0 | -1 |
| 1 |  3 | 1 | -1 |
| 1 |  5 | 0 |  0 |
| 1 |  5 | 0 |  0 |
| 1 | 10 | 0 |  1 |
| 1 | 10 | 1 |  1 |
| 2 |  3 | 0 | -1 |
| 2 |  3 | 1 |  0 |
| 2 |  4 | 0 |  0 |
| 2 |  4 | 1 |  0 |
+---+----+---+----+
</code>```

What I'm looking for, is given C, A, B, how can I make a prediction of what D will be. In this case, I will have historical data of all four values to go from. C won't necessarily be linear as in my example.

答:
This is a supervised learning problem.

It seems to be a classification task i.e. the output variable D takes class labels (the other group is the regression task).

There are a lot of algorithms for classification and you should probably start with something simple e.g. logistic regression.

If I misunderstood the example and yours is a symbolic regression task, a good approach is genetic programming (you have to specify a set of primitive and new equations are then formed by recombining previous equations).


问:
What are the data structures behind a spreadsheet?
I would like to understand how a spreadsheet (a group of named or otherwise identified cells containing values or formulas referencing other cells) is solved. I have tried looking at existing projects, but there was so much going on with the GUI, serialization, events, etc. that I couldn't find the spreadsheet.

At its simplest how does it work?

答:
I have coded a python package that allows you to convert MS Excel file objective function cells structure into Python. XL2py

Cell values are parsed to a dict() type object appends their values.
Cells with references to other cells by formulas comprise nodes.
Nodes refer to a cell whose value is defined by its formula. From each node formula, a dependency structure is defined so as to define whether circular references exists or not.
Node calculation orders are defined by taking into account involved cells dependency structures.

As of the I/O tree-structure, you may use any minimization algorithm implement in Python as your will.

I would suggest you take a look at https://github.com/gusmaogabriels/XL2py

Best regards, Gabriel


问:
Exception clutter, how necessary is it?
Let's say I have a few methods that access the File System, and I want them to be a bit robust, I want to throw errors so the user can react:

If the file doesn't have read / write rights, I want to inform him/her.

If the file does not exist, I want to prompt him/her to chose another one.

And so forth.

Thing is, the exceptions are cluttering the code a bit:

FileNotFoundException: quite necessary, the file was not found,
try again or give up.

IOException: This is usually when the file can't be read for whatever reason.

It was there, but now it's not, you don't have access rights any more,
something went horribly wrong. Generally this is a stopping point,
but still the user could choose another file or something, I'd rather
not crash the app.

InvalidPathException: Either the developer, or the user tried to give a bad
path (like including an illegal character in the file name, again,
the app should not crash because of this.

In my case I'd say all these exceptions are important because IOE captures FNFE, but they get resolved differently, and while FNFE and Invalid Path are similar, I still have to throw them separately, but at least catch them together.

My question is

When exceptions start piling up, the code starts to get ugly, I'm guessing there's no work around for this?

答:
Confine the crud necessitated by multiple exceptions to the smallest possible scope, and then wrap it into your own exception type that preserves all the original information.

To elaborate: say you have to deal with FileNotFoundException, PermissionsException, ReadOnlyFileSystemException and invalidpathException, and all of these don't have a common super type (or you don't want to dilute the information that much by catching plain IOException). What you should do is write a method that catches all of these different exceptions and rethrows a self-written PreferencesException in every case, just annotated with the orignal error information if needed. That way, every other method in your code base only has to deal with that exception type (or possibly with no type at all if your new exception type isn't a checked exception).

Title: Exception clutter, how necessary is it?


答:
Since the flow should be the same with the 3 kinds of exceptions:

The user choose a file

If the file couldn't be openend (either because the file doesn't exist, is locked, invalid path, ...), prompt him with a custom message

Allow the user to retry the operation

I suggest to create a custom class inheriting from Exception.
In this exception you should wrap:

the original exception (IOE, FNFE, IPE) to preserve the stacktrace

a custom message that could be displayed to the user (or a key to a i18n string if you need)

Example:

```<code>public final class FileException extends Exception {
    public FileException(String message, Throwable cause) {
        super(message, cause);
    }
}
</code>```

The most important step in your code is to throw a FE like this:

```<code>try {
    //some operation that can throw an FNFE
}
catch(FileNotFoundException e) {
    throw new FileException("The file doesn't exist !", e);
}
</code>```

Title: Exception clutter, how necessary is it?

Body:
Let's say I have a few methods that access the File System, and I want them to be a bit robust, I want to throw errors so the user can react:

If the file doesn't have read / write rights, I want to inform him/her.

If the file does not exist, I want to prompt him/her to chose another one.

And so forth.

Thing is, the exceptions are cluttering the code a bit:

FileNotFoundException: quite necessary, the file was not found,
try again or give up.

IOException: This is usually when the file can't be read for whatever reason.

It was there, but now it's not, you don't have access rights any more,
something went horribly wrong. Generally this is a stopping point,
but still the user could choose another file or something, I'd rather
not crash the app.

InvalidPathException: Either the developer, or the user tried to give a bad
path (like including an illegal character in the file name, again,
the app should not crash because of this.

In my case I'd say all these exceptions are important because IOE captures FNFE, but they get resolved differently, and while FNFE and Invalid Path are similar, I still have to throw them separately, but at least catch them together.

My question is

When exceptions start piling up, the code starts to get ugly, I'm guessing there's no work around for this?

Body:
Since the flow should be the same with the 3 kinds of exceptions:

The user choose a file

If the file couldn't be openend (either because the file doesn't exist, is locked, invalid path, ...), prompt him with a custom message

Allow the user to retry the operation

I suggest to create a custom class inheriting from Exception.
In this exception you should wrap:

the original exception (IOE, FNFE, IPE) to preserve the stacktrace

a custom message that could be displayed to the user (or a key to a i18n string if you need)

Example:

public final class FileException extends Exception {
    public FileException(String message, Throwable cause) {
        super(message, cause);
    }
}

The most important step in your code is to throw a FE like this:

try {
    //some operation that can throw an FNFE
}
catch(FileNotFoundException e) {
    throw new FileException("The file doesn't exist !", e);
}


问:
What HTTP status using for REST search query which returns nos results
I'm wondering how to manage empty results returned by search queries in a REST web-service :

I there was a query like my_ressource_collection/{id} and the resource didn't exists i would return 404 - Not Found

But, if my URI is more like a search query like : my_ressource_collection/?fromDate={fromDate}&toDate={toDate}&filter1={filter1}&page={page} : Does the same logic applies ?
If no results matchs to the perametters, do I have to return a 404 status ?

答:
I think in the most cases the most useful reaction would be to return a regular answer (HTTP 200) and send empty data.
For example if you are returning JSON you could send

```<code>{}
</code>```

Another good option may be the HTTP Code '204 - No Content'.

The 4xx codes describe a client failure, so the 404 code wouldn't be a good idea, because it's a valid request, even if there are no matching data.

Body:
I think in the most cases the most useful reaction would be to return a regular answer (HTTP 200) and send empty data.
For example if you are returning JSON you could send

{}

Another good option may be the HTTP Code '204 - No Content'.

The 4xx codes describe a client failure, so the 404 code wouldn't be a good idea, because it's a valid request, even if there are no matching data.


答:
No, the same logic does not apply.

204 is the most result for this scenario.

See, the 4xx implicit means that the someone "messed-up" somehow. Either the user entered some invalid info or the interface implementer did not used the Rest API properly, anyhow, the request need some "touch-up"... In the first example, the user entered a invalid info (the id), but in the second, as long as he entered a valid date and etc, no mistakes were made, hence the request was understood and completed with no errors.

200 with a empty JSON is not the best approach because it might lead API users to believe that an error occurred or something.

Title: What HTTP status using for REST search query which returns nos results

Body:
I'm wondering how to manage empty results returned by search queries in a REST web-service :

I there was a query like my_ressource_collection/{id} and the resource didn't exists i would return 404 - Not Found

But, if my URI is more like a search query like : my_ressource_collection/?fromDate={fromDate}&toDate={toDate}&filter1={filter1}&page={page} : Does the same logic applies ?
If no results matchs to the perametters, do I have to return a 404 status ?


问:
Why are the sizes of programs so large?
If we look at the vintage program Netscape Navigator or an early version of Microsoft Word, those programs were less than 50 MB in size. Now when I install google chrome it is 200 MB and desktop version of Slack is 300 MB. I read about some rule that programs will take all available memory no matter how much it is but why?

Why are the current sizes of programs so large compared to 10 or 15 years ago? The programs are not doing significantly more functions and do not look very different. What is it that is the resource hog now?

答:
It may be true that programs tend to expand to fill available space, similar to the suburban phenomena where you add new lanes to a gridlocked superhighway and within a few years traffic is backed up again.

But if you look into it you may find that they programs actually do more stuff.  Browsers, for example, run fancier graphics, have slick developer tools that did not exist a few years ago, etc.  They also link to many libraries, sometimes using just a small portion of the code.  So while programs may increase in size to fill available memory, some of that may be fore legitimate reasons.

Title: Why are the sizes of programs so large?


问:
Code First Approach and Business Classes Validation
I have a solution split into two projects : A class library containing all of my model classes (lets call it Business), and an ASP.Net MVC project.

My Business classes are meant to be generic and work for multiple types of projects. For this reason, they don't contain any data annotations/associations to other classes, only member variables/properties/constructors.

Using the code-first approach, how should I design my ASP.Net models to work with my Business models.

My initial taught was setting my Business classes as partial classes and then overwrite my properties by adding the necessary data annotations/associations. I can't do that because we are dealing with two separate projects.

I was also thinking that I could use inheritance. My ASP.Net models could inherit from the Business classes and I could add my data annotations/associations on top of that. This seems a bit messy and illogical though, as I would need to define all of my constructors in this new subclass.

Is there a smart way of doing this in a cleanly?

EDIT :

My Business classes have validations by throwing exceptions in the property setters. My first design was to create my own custom data annotation that will catch the exceptions thrown by my setters :

```<code>public class SetterBasedValidation : ValidationAttribute
    {
        string m_errorMessage = null;
        public SetterBasedValidation(string errorMessage)
        {
            m_errorMessage = errorMessage;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            try
            {
                Type type = validationContext.ObjectType;
                PropertyInfo property = type.GetProperty(validationContext.MemberName);
                property.SetValue(validationContext.ObjectInstance, value);
            }
            catch (Exception)
            {
                return new ValidationResult(m_errorMessage);
            }

            return ValidationResult.Success;
        }
    }
</code>```

I would then need a way to use my custom data annotation in my ASP.Net model class. This would give me the result I want :

Keep my Business classes generic

Use the validations from my setters

Use data annotations

EDIT 2 :

Here is a basic overview of what my solution setup looks like.
My business classes (domain models) contains code looking like this :

```<code> public class User
    {

        private string m_name = null;

        public string Name
        {
            get { return m_name; }
            set
            {
                string name = value.Trim();

                if (name.Length > 20 || name.Length < 1)
                {
                    throw new ArgumentException("Name length invalid.");
                }
                m_name = name;
            }
        }
    }
</code>```

答:
Your website should have a separate set of ViewModels which wrap the domain models and any other data/logic required by the page.

Because these view models belong to the website rather than the domain its ok to stick on any validation or extra logic which is only required by the website/View for the particular process you are implementing.

I think the best example is say you have some process 'Sign Up' the domain model for which includes a ton of data about the person signing up. Your design teams comes up with two designs.

Design 1: A large single page form with all the fields on

Design 2: A 'Wizard' approach with multiple separate forms

Although both designs use the same underling logic for signing up. each will have very different view models.

update ---

Entity Framework data annotations allow EF to correctly map your object to a database table. There are some conventions which will allow you to get away with not using some of them of your properties are named as expected.

However, you are correct in that if you want to separate your domain objects from the persistence logic you will need to implement an Entity Object which mirrors the properties on your domain object and to which you can add the data annotations.

You can wrap all this in a repository object which can get the Entity objects back from the DB, convert them to your Domain objects and return them to the calling code. However if you do all these things you will find that you have lost the time saving benefits of EF and might as well have just used SqlClient

In the ideal world you solution structure might look like this:

```<code>DomainModels - class lib
    User.cs

EntityModels - class lib
    UserEntity.cs - with data annotations

RepositoryEF - class lib ref domain and entity
    UserRepository.cs - eg. public User GetUser(string id)

Website - ref the other three
    UserController.cs - calls repository to get a domain object
    UserViewModel.cs - populated from domain object by controller
    UserView.cshtml - uses viewmodel as its model and displays data to user
</code>```

Body:
Your website should have a separate set of ViewModels which wrap the domain models and any other data/logic required by the page.

Because these view models belong to the website rather than the domain its ok to stick on any validation or extra logic which is only required by the website/View for the particular process you are implementing.

I think the best example is say you have some process 'Sign Up' the domain model for which includes a ton of data about the person signing up. Your design teams comes up with two designs.

Design 1: A large single page form with all the fields on

Design 2: A 'Wizard' approach with multiple separate forms

Although both designs use the same underling logic for signing up. each will have very different view models.

update ---

Entity Framework data annotations allow EF to correctly map your object to a database table. There are some conventions which will allow you to get away with not using some of them of your properties are named as expected.

However, you are correct in that if you want to separate your domain objects from the persistence logic you will need to implement an Entity Object which mirrors the properties on your domain object and to which you can add the data annotations.

You can wrap all this in a repository object which can get the Entity objects back from the DB, convert them to your Domain objects and return them to the calling code. However if you do all these things you will find that you have lost the time saving benefits of EF and might as well have just used SqlClient

In the ideal world you solution structure might look like this:

DomainModels - class lib
    User.cs

EntityModels - class lib
    UserEntity.cs - with data annotations

RepositoryEF - class lib ref domain and entity
    UserRepository.cs - eg. public User GetUser(string id)

Website - ref the other three
    UserController.cs - calls repository to get a domain object
    UserViewModel.cs - populated from domain object by controller
    UserView.cshtml - uses viewmodel as its model and displays data to user


问:
Should every member of a team use the same IDE?
Do you think it makes sense to enforce that every member of a team must use the same IDE?

For instance all engineers that are already on the team use IDE X. Two new engineers come and want to use IDE Y instead because that's what they have been using for several years now.

Do you have any experience with "mixed IDE" teams? If so what is it?

答:
YES!
Enforce singleton IDE.

It makes problems when the project dependency change. if one introduce a new dependency to the project, then every one will waste time to introduce that new dependency, and some might fail and waste time on that process. HUGE WASTE OF TIME.

there should be a REALLY good justification to add a different IDE to the team, meaning the saved time should surpass the time dedicated to migrate the system to different IDEs

ContentLicense: CC BY-SA 2.5


问:
Is mutually referencing classes a consequence of bad design?
I am currently working on a small game I did in about ten days. Since I am programming for myself, I am being lazy and going to the easiest solution with (too) little concern about bad code quality.

However I am reaching a point where it begins to matter. I am starting to move booleans that references states into classes etc. and now I wanted to know experienced programmers opinion about mutual referencing objects.

What I mean by mutual referencing objects is this: we have a server which can create multiple games, such as chess games when two clients connect to play. Everytime a player makes a move, his connection handler must update a specific board on the server. After the update, once the board is updated, a broadcast of the new state needs to be done to each client.

I found convenient to have two Client objects in the Board (so Board can Client.send() to both) and a Board in each Client (so Client can call Board.update (move)). For some reason, I'm inclined to think this is generally bad and could be avoided, but what is your opinion ?

Is this fine as it is, or am I missing something here ?

答:
Having classes directly depend on each other is known as coupling.  It's generally taken as an article of faith, with no explanation provided because apparently none should even be needed, that coupling is a Bad Thing because it makes your system "inflexible."

The problem is, the only thing worse than too little flexibility is too much flexibility.  When you make everything as flexible as possible, you end up with horrible messes like Soft Coding.  And that inflexibility can actually be a huge benefit by turning the perceived disadvantage on its head.  The disadvantage frequently cited is that if you change one thing, it will break everything it's coupled to and you'll have to change that too.  But consider this: changes to one subsystem frequently (not always, but more often than you'd like!) do end up affecting related subsystems anyway.  If they're strongly coupled, and your language has a strong, static type system, then when you make a breaking change, the compiler will do all the hard work for you and show you exactly what has to be fixed and where.  The more you decouple things, the harder it is to track down problems like this.

Which is not to say that everything should be strongly coupled, of course, especially if you want your code to be able to work with different types of related systems.  People call too much coupling a maintenance nightmare for a good reason.  But be careful of just decoupling everything for the sake of decoupling everything, because that can be even worse.

In this particular case, it looks like you're not trying to make your code work with multiple different types of systems.  Your Client isn't trying to be able to run "a chess Board, a checkers Board, a backgammon Board or a Scrabble Board"; it's simply playing chess.  So having it know about the Board class isn't a problem.  Likewise, the Board isn't trying to communicate with multiple different clients, so it doesn't need to be flexible in the type of client it tries to communicate with, and therefore, you don't need the added complexity that comes with making it flexible.  This is a very important pragmatic programming principle known as YAGNI (You ain't gonna need it!)  Keep that in mind, and you should do fine.


答:
Either a 204 NoContent or a 200 OK would be fine as long as that is communicated to the consumer in some way.

A query returning an empty result set is not uncommon in programming and therefor shouldn't be strange at an API layer either.

Personally It would depend on the type of query being performed in my API. A standard query that normally returns several rows of data if the parameters match would make me lean towards a 200 OK with an empty result matching the normal behavior of the query.

Ex in JSON:

```<code>{
    'results' : [
    ]
}
</code>```

However if the query itself was meant to be a location component, think a complicated routing issue, then I would return a 204 NoContent or even a 404 Not Found depending on the severity, so that the consumer could recognize the issue and take additional actions.

Body:
Either a 204 NoContent or a 200 OK would be fine as long as that is communicated to the consumer in some way.

A query returning an empty result set is not uncommon in programming and therefor shouldn't be strange at an API layer either.

Personally It would depend on the type of query being performed in my API. A standard query that normally returns several rows of data if the parameters match would make me lean towards a 200 OK with an empty result matching the normal behavior of the query.

Ex in JSON:

{
    'results' : [
    ]
}

However if the query itself was meant to be a location component, think a complicated routing issue, then I would return a 204 NoContent or even a 404 Not Found depending on the severity, so that the consumer could recognize the issue and take additional actions.


答: The poor mans approach here is to create a Mediator design pattern, where the two classes mentioned only communicate to the mediator and the mediator knows about the two classes. You can take that as far as little as you desire with interfaces instead of concrete classes, factories to build the components, so on, but a mediator will definitely make any possible refactor simpler down the road!</p>

Title: Is mutually referencing classes a consequence of bad design?

Body:
I am currently working on a small game I did in about ten days. Since I am programming for myself, I am being lazy and going to the easiest solution with (too) little concern about bad code quality.

However I am reaching a point where it begins to matter. I am starting to move booleans that references states into classes etc. and now I wanted to know experienced programmers opinion about mutual referencing objects.

What I mean by mutual referencing objects is this: we have a server which can create multiple games, such as chess games when two clients connect to play. Everytime a player makes a move, his connection handler must update a specific board on the server. After the update, once the board is updated, a broadcast of the new state needs to be done to each client.

I found convenient to have two Client objects in the Board (so Board can Client.send() to both) and a Board in each Client (so Client can call Board.update (move)). For some reason, I'm inclined to think this is generally bad and could be avoided, but what is your opinion ?

Is this fine as it is, or am I missing something here ?


问:
Domain Model, validation, and pushing errors to the model
Looking into DDD and something I noticed is that business logic should be in the model, otherwise you just have property bags.  That said how do you handle pieces of validation that require a trip to the database?

For example, you have an domain object that represent categories for a blogging engine.

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
```

<p>From a developer's perspective, you could create an empty category, but this isn't valid in the business world.  A <code>Category</code> <strong>requires</strong> a Name to be a valid category, therefore we end up with:</p>

<pre class="lang-cs prettyprint-override"><code>public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Category(string name)
    {
        Name = name;
    }
}
</code>```

Now, a Category can't be created without a name.  But, we can't have duplicate Category names either, that would just cause confusing and redundancy.  I don't want the entity to handle it themselves because this would end up more of an Active Record Pattern and I don't want the model to be "self-aware/persisting" so to speak.

So to this point, where should this validation take place.  It is important that if the user types an duplicate Category, we would notify the user of this.  Should there be a "service" layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?

Someone please set me straight because I really like where DDD is going, I just can't make all the connections to get there myself.

答:
What I do is that I build my subjects (subordinates, objects within a domain) in such a way that they can never be instantiated by anyone other than the domain itself. (The main or central domain object.)  This is in line with best practices: never use the new operator to instantiate objects that do not belong to you, (objects from other packages/namespaces/assemblies,) always invoke factories to do that.  The domain is in a position of using new to instantiate its own subjects, because they belong to it.

Instantiation of subjects only by the domain can be enforced by declaring their constructors as package-private, (assembly-internal,) or, better yet, by declaring the subject classes themselves as package-private, (assembly-internal,) and having them implement public interfaces, (interfaces exposed by the domain,) so that the outside world cannot even think of instantiating them.

So, since subjects can only be instantiated by the domain, it is very easy to have the domain perform the necessary validation when creating them, as another answer suggested, so as to ensure that the subjects are valid right from the start.

However, this does not completely solve the problem, because you may later want to rename a subject, (store a different name in it,) in which case you must again be prevented from giving it a name which is already taken by a different subject.  Clearly, access to the database is needed at all times, in order to provide a complete service.

So, the solution that I have found for this is that every subject knows its domain.

The domain is always passed as the first parameter to the constructor of every subject.  Every single instantiation of a subject by the domain looks like this: new Subject( this, ... ). In a sense, the role played by the domain in domain-driven programming parallels the role played by the object in object-oriented programming: Just as every method accepts as a hidden first parameter the this pointer, which points to the object, so does every subject accept as its first constructor parameter the domain pointer, which points to the domain.

Thus, each and every subject is perfectly capable of performing whatever validation is necessary, by invoking the domain to do its validation.

If you do not want your subjects to be tied to the domain, then your subjects may be thought of as having an extra state, indicating whether they are at any given moment parts of a domain or not. (persisted or not, equivalent to the "attached/detached" state of Hibernate.)  So, an object may begin its life as not part of the domain, (not persisted, detached in Hibernate parlance,) in which case it cannot perform any validation, and later it may become part of the domain, (persisted, attached in Hibernate parlance,) at which point it receives a reference to the domain, and it may do whatever validation is necessary.  Later you may even remove it from the domain, (detach it,) at which point you would presumably nullify the domain pointer and the object would again be unable to perform validation.


问:
Java abstract class naming
Example:

You create an abstract class for Ajax actions. Different Ajax actions will all extend this class.

Problem:

Do you name the class AjaxAction or AbstractAjaxAction?

When you create subclasses, do you name them:

Action

AjaxAction

Just name them what they are

I have not been able to find what the "official" convention is. I don't see a need for the "Abstract" prefix or any required naming convention in the subclasses. (It may fit anyway, depending.)

Is there an official convention? Could you link me to it? And what are your opinions on this subject?

答: I would name the abstract class AjaxActionBase and suffix child classes with either 'Action' or 'AjaxAction', whichever ended up more naturally readable for the actions I needed to create.

Title: Java abstract class naming


答:
HTTP status codes are specific to the HTTP protocol.  So, if the request is successful, meaning, nothing went wrong with the HTTP negotiation, then you should return HTTP status 200 OK.

The fact that the number of result rows in a successfully completed query happens to be zero is completely irrelevant to the protocol that you use for communication.

So, do not mix the two: return a perfectly valid successful response, carrying an empty result set.

As a matter of fact, in my opinion, even if the execution of your query resulted in an error like "unknown table or view", you should still not mix error codes which are specific to your application with HTTP error codes.  As far as HTTP is concerned, there was a perfectly valid HTTP request, which is now receiving a perfectly valid HTTP response, and any information about what your application did while servicing the request, like what the results are, or why the results could not be obtained, should be included within the application-specific payload of the response, and is none of HTTP's business.


问:
Deleting subtrees in hierarchical agreggates
I am working on a file-system-like application where I use CQRS/event-sourcing to handle the state of folders and files (creating, moving, renaming, etc). Each node (folder or file) is represented by a single aggregate (as they are standalone unit with own ID). Now I am about to implement deleting of the nodes, where the system is capable, of course, deleting a whole subtree of nodes (= delete a folder containing other folders and files).

Now I quite don't know how to handle this in CQRS style because the command, as I learned, should operate on a single aggregate.

One idea I had is to create a saga which would be created by FolderDeleteStarted event and the responsibility of the saga would be to create commands for each of the child nodes, resulting in cascading creation of sagas for each child folder. Saga would ensure to delete the parent folder once all the commands for child folders would be finished, so it would be blocking. Saga would run in separate thread so the initial command for deleting folder will be still async.

However I don't really like the idea of cascading sagas.

I am new to CQRS and still learning the basics. I would love to know how you would solve similar situation.

答:
I have tried cascading sagas (actually process managers in this case, but I will retain the saga term below) with some success. It worked like this:

```<code>aggregate - DeleteNode 1  -> NodeDeleted 1
saga      - NodeDeleted 1 -> child nodes 2, 3
                             DeleteNode 2
                             DeleteNode 3
aggregate - DeleteNode 2  -> NodeDeleted 2
aggregate - DeleteNode 3  -> NodeDeleted 3
saga      - NodeDeleted 2 -> no child nodes
saga      - NodeDeleted 3 -> no child nodes
</code>```

Problems

Cycles (e.g. if following links).

Make sure they are detected and exit early or infinite loop will happen

Might be necessary to enrich the event to include previous deletion paths for detecting cycles in saga

Multi-parent (via links again).

Be prepared to handle that in the aggregate

Fail 2nd deletion attempt b/c it's already deleted

Your concurrency strategy comes into play here

In my case, I had both of these problems initially. We corrected the data to not have cycles and added a validation to prevent it in the future. However, multi-parent of a child node was a required feature. It caused unnecessary extra commands against the same subnodes. There was still an edge case we hadn't tracked down where the cascade would stop early. It happened less than 10 times a year, and we simply ran a recalculate command on the item to fix it.

A better way

The above is complicated and has edge cases that might not be covered.

Instead of using a cascading saga, another option is to have your command handler for this use case recursively load all descendant nodes of the node being deleted and record their IDs (do not actually call delete on the child nodes here as that would require a transaction spanning aggregates). Then as part of your delete use case on your aggregate node, pass in the array of all descendant node ids. Your aggregate likely knows its immediate children IDs, but not all descendants.

Then your saga would have enough information to send commands to delete all descendants at once. It would be a different delete command so as not to be recursive, because you already did the recursive work up front when deletion was requested by the user.

```<code>aggregate DeleteNode 1 [2,3] -> NodeDeleted 1 [2,3]
saga      NodeDeleted 1 [2,3] -> DeleteNodeInternal 3
                                 DeleteNodeInternal 2
aggregate DeleteNodeInternal 3 -> NodeDeletedInternal 3
          DeleteNodeInternal 2 -> NodeDeletedInternal 2
</code>```

--Update--

This method above still does not cover the case where nodes are added to descendants of the deleted parent while the saga is still sending delete commands. To cover that, you can keep a tree structure of the deleted nodes in the initial deletion event. Then when the saga tries to delete a node, it sends with it the expected children of that node. When the expected children and actual children don't match, then emit another event for the saga to resolve that situation.

```<code>aggregate DeleteNode 1 [2,3] -> NodeDeleted 1 [2,3]
saga      NodeDeleted 1 [2,3] -> DeleteNodeInternal 3
                                 DeleteNodeInternal 2
aggregate DeleteNodeInternal 3 [] -> NodeDeletedInternal 3
                                     ChildEscapedDeletion 4
          DeleteNodeInternal 2 [] -> NodeDeletedInternal 2
saga      ChildEscapedDeletion 4 -> DeleteNode 4
</code>```

Body:
I have tried cascading sagas (actually process managers in this case, but I will retain the saga term below) with some success. It worked like this:

aggregate - DeleteNode 1  -> NodeDeleted 1
saga      - NodeDeleted 1 -> child nodes 2, 3
                             DeleteNode 2
                             DeleteNode 3
aggregate - DeleteNode 2  -> NodeDeleted 2
aggregate - DeleteNode 3  -> NodeDeleted 3
saga      - NodeDeleted 2 -> no child nodes
saga      - NodeDeleted 3 -> no child nodes

Problems

Cycles (e.g. if following links).

Make sure they are detected and exit early or infinite loop will happen

Might be necessary to enrich the event to include previous deletion paths for detecting cycles in saga

Multi-parent (via links again).

Be prepared to handle that in the aggregate

Fail 2nd deletion attempt b/c it's already deleted

Your concurrency strategy comes into play here

In my case, I had both of these problems initially. We corrected the data to not have cycles and added a validation to prevent it in the future. However, multi-parent of a child node was a required feature. It caused unnecessary extra commands against the same subnodes. There was still an edge case we hadn't tracked down where the cascade would stop early. It happened less than 10 times a year, and we simply ran a recalculate command on the item to fix it.

A better way

The above is complicated and has edge cases that might not be covered.

Instead of using a cascading saga, another option is to have your command handler for this use case recursively load all descendant nodes of the node being deleted and record their IDs (do not actually call delete on the child nodes here as that would require a transaction spanning aggregates). Then as part of your delete use case on your aggregate node, pass in the array of all descendant node ids. Your aggregate likely knows its immediate children IDs, but not all descendants.

Then your saga would have enough information to send commands to delete all descendants at once. It would be a different delete command so as not to be recursive, because you already did the recursive work up front when deletion was requested by the user.

aggregate DeleteNode 1 [2,3] -> NodeDeleted 1 [2,3]
saga      NodeDeleted 1 [2,3] -> DeleteNodeInternal 3
                                 DeleteNodeInternal 2
aggregate DeleteNodeInternal 3 -> NodeDeletedInternal 3
          DeleteNodeInternal 2 -> NodeDeletedInternal 2

--Update--

This method above still does not cover the case where nodes are added to descendants of the deleted parent while the saga is still sending delete commands. To cover that, you can keep a tree structure of the deleted nodes in the initial deletion event. Then when the saga tries to delete a node, it sends with it the expected children of that node. When the expected children and actual children don't match, then emit another event for the saga to resolve that situation.

aggregate DeleteNode 1 [2,3] -> NodeDeleted 1 [2,3]
saga      NodeDeleted 1 [2,3] -> DeleteNodeInternal 3
                                 DeleteNodeInternal 2
aggregate DeleteNodeInternal 3 [] -> NodeDeletedInternal 3
                                     ChildEscapedDeletion 4
          DeleteNodeInternal 2 [] -> NodeDeletedInternal 2
saga      ChildEscapedDeletion 4 -> DeleteNode 4


问:
Is it wasteful to create a new database table instead of using enum data type?
Suppose I have 4 types of services I offer (they are unlikely to change often):

Testing

Design

Programming

Other

Suppose I have 60-80 of actual services that each fall into one of the above categories.  For example, 'a service' can be "Test Program using technique A" and it is of type "Testing".

I want to encode them into a database.  I came up with a few options:

Option 0:

Use VARCHAR directly to encode service type directly as a string

Option 1:

Use database enum.  But, enum is evil

Option 2:

use two tables:

```<code>service_line_item (id, service_type_id INT, description VARCHAR);
service_type (id, service_type VARCHAR);
</code>```

I can even enjoy referential integrity:

```<code>ALTER service_line_item
    ADD FOREIGN KEY (service_type_id) REFERENCES service_type (id);
</code>```

Sounds good, yes?

But I still have to encode things and deal with integers, i.e when populating the table.  Or I have to create elaborate programming or DB constructs when populating or dealing with the table.  Namely, JOINs when dealing with the database directly, or creating new object oriented entities on the programming side, and making sure I operate them correctly.

Option 3:

Don't use enum, do not use two tables, but just use an integer column

```<code>service_line_item (
    id,
    service_type INT,        -- use 0, 1, 2, 3 (for service types)
    description VARCHAR
);
</code>```

This is like a 'fake enum' that requires more overhead on the code side of things, like i.e. knowing that {2 == 'Programming'} and dealing with it appropriately.

Question:

Currently I have implemented it using Option 2, guided under concepts

do not use enum (option 1)

avoid using a database as a spreadsheet (option 0)

But I can't help to feel that seems wasteful to me in terms of programming and cognitive overhead -- I have to be aware of two tables, and deal with two tables, vs one.

For a 'less wasteful way', I am looking at Option 3.  IT is lighter and requires essentially the same code constructs to operate (with slight modifications but complexity and structure is basically the same but with a single table)

I suppose ideally it is not always wasteful, and there are good cases for either option, but is there a good guideline as to when one should use Option 2 and when Option 3?

When there are only two types (binary)

To add a bit more to this question... in the same venue, I have a binary option of "Standard" or "Exception" Service, which can apply to the service line item.  I have encoded that using Option 3.

I chose not to create a new table just to hold values {"Standard", "Exception"}.  So my column just holds {0, 1} and my column name is called exception, and my code is doing a translation from {0, 1} => {STANDARD, EXCEPTION} (which I encoded as constants in programming language)

So far not liking that way either..... (not liking option 2 nor option 3).
I do find option 2 superior to 3, but with more overhead, and still I cannot escape encoding things as integers no matter which option I use out of 2, and 3.

ORM

To add some context, after reading answers - I have just started using an ORM again (recently), in my case Doctrine 2.  After defining DB schema via Annotations, I wanted to populate the database.  Since my entire data set is relatively small, I wanted to try using programming constructs to see how it works.

I first populated service_types, and then service_line_items, as there was an existing list from an actual spreadsheet.  So things like 'standard/exception' and 'Testing' are all strings on the spreadsheet, and they have to be encoded into proper types before storing them in DB.

I found this SO answer: What do you use instead of ENUM in doctrine2?,
which suggested to not use DB's enum construct, but to use an INT field and to encode the types using 'const' construct of the programming language.

But as pointed out in the above SO question, I can avoid using integers directly and use language constructs -- constants -- once they are defined....

But still .... no matter how you turn it, if I am starting with string as a type, I have to first convert it to a proper type, even when using an ORM.

So if say $str = 'Testing';, I still need to have a block somewhere that does something like:

```<code>switch($str):
{
    case 'Testing':  $type = MyEntity::TESTING; break;
    case 'Other':    $type = MyEntity::OTHER; break;
}
</code>```

The good thing is you are not dealing with integers/magic numbers [instead, dealing with encoded constant quantities], but the bad thing is you can't auto-magically pull things in and out of the database without this conversion step, to my knowledge.

And that's what I meant, in part, by saying things like "still have to encode things and deal with integers".  (Granted, now, after Ocramius' comment, I won't have to deal directly with integers, but deal with named constants and some conversion to/from constants, as needed).

答:
Option #2, using reference tables, is the standard way of doing it.  It has been used by millions of programmers, and is known to work. It is a pattern, so anyone else looking at your stuff will immediately know what is going on. There exist libraries and tools that work on databases, saving you from lots and lots of work, that will handle it correctly.  The benefits of using it are innumerable.

Is it wasteful?  Yes, but only slightly.  Any half-decent database will always keep such frequently joined small tables cached, so the waste is generally imperceptible.

All other options that you described are ad hoc and hacky, including MySQL's enum, because it is not part of the SQL standard.  (Other than that, what sucks with enum is MySQL's implementation, not the idea itself.  I would not mind seeing it one day as part of the standard.)

Your final option #3 with using a plain integer is especially hacky.  You get the worst of all worlds: no referential integrity, no named values, no definitive knowledge within the database of what a value stands for, just arbitrary integers thrown all over the place.  By this token, you might as well quit using constants in your code, and start using hard-coded values instead. circumference = radius * 6.28318530718;.  How about that?

I think you should re-examine why you find reference tables onerous.  Nobody else finds them onerous, as far as I know.  Could it be that it is because you are not using the right tools for the job?

Your sentence about having to "encode things and deal with integers", or having to "create elaborate programming constructs", or "creating new object oriented entities on the programming side", tells me that perhaps you may be attempting to do object-relational mapping (ORM) on the fly dispersed throughout the code of your application, or in the best case you may be trying to roll your own object-relational mapping mechanism, instead of using an existing ORM tool for the job, such as Hibernate.  All these things are a breeze with Hibernate.  It takes a little while to learn it, but once you have learned it, you can really focus on developing your application and forget about the nitty gritty mechanics of how to represent stuff on the database.

Finally, if you want to make your life easier when working directly with the database, there are at least two things that you can do, that I can think of right now:

Create views that join your main tables with whatever reference tables they reference, so that each row contains not only the reference ids, but also the corresponding names.

Instead of using an integer id for the reference table, use a CHAR(4) column, with 4-letter abbreviations.  So, the ids of your categories would become "TEST", "DSGN", "PROG", "OTHR". (Their descriptions would remain proper English words, of course.)  It will be a bit slower, but trust me, nobody will notice.

Finally, when there are only two types, most people just use a boolean column.  So, that "standard/exception" column would be implemented as a boolean and it would be called "IsException".

ContentLicense: CC BY-SA 4.0


问:
Checking for nil in Go
In Go, is it idiomatic to check for nil and return an error if a parameter is nil?

Should pointer method receivers ever include nil checks?

I've seen a lot of code in other languages where people applying defensive programming also checked for nulls and threw an exception when a null was passed in. I am wondering if the Go-equivalent, checking for nil and returning an error, is idiomatic in Go. Say some function returns nil for some reason and you pass in nil into another function. This function doesn't handle nils and somewhere down the stack inside of the function a "kaboom" occurs, leaving the caller wondering whether the error is inside of the abstraction or in his calling code.

答:
Checking for nil, and returning an error is not a pattern I have seen in Go (I have been using it professionally for about 6 months at the moment).

If a function that does not allow nil, e.g. a pointer method receiver, is called with a nil value, that is a programming error - and when an error is caused by something that is a programming error I think that the idiomatic solution is to panic which is actually what will happen when the pointer is dereferenced.

As an example in the go library, the reflect package has plenty of methods that can panic when called incorrectly. E.g. Value.Float() will panic if the Value instance does not refer to a floating point value.

error return values are, from what I can tell, not so much to communicate programming errors, but rather situations happening outside the control of your application, e.g. cannot connect to database, file cannot be written to, network connection lost, etc.

I have certainly not checked the receiver in pointer method receivers in the Go code I have written.

Title: Checking for nil in Go


问:
Uncaught TypeError: Cannot read property 'add' of null
I am novice developer.

While development is going on, we come across different error issues. However for the novice of programming, it is always hard to directly understand them & solve them.

I believe, errors are generally related to typing error OR data structure error OR run-time memory error - which is related to hardware OR else.

How to elaborate and solve those errors very fast ?

答:
I have to disagree with the need or usefulness of a debugger. In any multi-threaded environment a debugger is next to useless especially in an embedded platform. printf FTW!! For a novice programmer my suggestion would be start keeping a list of common mistakes you make.

For example:
Are you checking all your return values?
Are you checking for boundary conditions?
Are you initializing all your variables?
Are you checking for NULL before dereferencing a pointer?
Are you validating all you input parameters?
Are your linked list insertions and deletions correct?
Do you have the correct protection mechanisms around shared data/resources.

After you gain more experience knowing where to start looking for problems become more intuitive. I think the hardest part about being a novice program is lack of knowledge/experience with the platform they start working on. I used to be amazed when a more senior developer would look at a bug that I was working on and solve it 10mins after I had worked on it for 2 days. They were not any smarter than me, but the knowledge of how the system worked including how different subsystems interacted allowed them to make an educated hypothesis about what was going on based on the behavior of the bug. I can not stress enough how helpful it is to know as much about the platform that you are working as you can. Know your limits and do not be afraid to ask the more senior people for help. Also, if they do happen to help you make SURE that you have them explain exactly what was going on and make SURE that YOU understand what was causing the bug. Each bug is another opportunity to learn more about the platform that you are working on. The more you know the easy it is to debug.


问:
Is it okay to use a short EULA?
I need to add an EULA to my (commercial) software but I cannot afford a lawyer. Also I had a look at various EULA examples on the internet but they are all for specific software or countries, and are probably copied from other commercial software.

So I'm thinking about using a short custom EULA which would just mention the essential. Something like:

You may redistribute the trial version of this software

If you buy a license, you may not redistribute it or sell it

You may not sue me for any financial or material loss arising from the use of this software

This software is copyright XXX, all rights reserved.

Would that kind of EULA protect me in most cases? Also do you know of any company that use short EULA?

答: No. It is not okay to use a short EULA. The justice system is adversarial and your adversary is human. If you can make your adversary weary, confused, and doubtful then you must. You are not writing software or constructing a building where efficiency is a consideration and costs have to be justified. The words in a contract can be compared to spam and it is easy to produce spam. Every programmer knows refactoring software for brevity is hard work and refactoring a contract is likewise. In this case the lawyer will take the path of least resistance. The only limit to the length and complexity of a contract is the point where the one writing the contract becomes confused and doubtful but that point is well beyond the point that most readers can tolerate.</p>

Title: Is it okay to use a short EULA?


问:
Why is .NET VM based?
Java has been designed to run on a virtual machine to allow portability for programs.

However .NET has been designed from the start specifically for Windows.

Than what is the reason for .NET applications being compiled to bytecode for the CLR?

Was it simply to copy Java? Or is there a technical advantage to just compiling natively?

答:
Eric Lippert has a good explanation of why the .NET languages target IL instead of directly generating binary files titled Why IL?.

The reason is that the cost/effort of developing your compiler is cheaper/simpler with this approach. Your high level language compiler generates a common intermediate language. This makes it easy to add new languages as there is only one platform to generate code for. Then you have your 2nd stage compilers that take this intermediate language and output the platform specific binary (OS and CPU architecture).

This way, each time you add support for a new platform (such as a new processor), you just need to write a single compiler that compiles IL to the new platform.

Title: Why is .NET VM based?


问:
What are the key differences between low-level C development and higher level OOP development?
I have been using high-level OOP language (like C# and/or Java) for quite some time. I know patterns like the gang of four, can read and write code reasonably well and am considered a senior by his peers.

I am moving to low-level C development. As a result of my background I am unfamiliar with many of the technologies and skills inherent in lower level development/implementation.

What are the key differences in the technology and approach to development that I need to understand in order to be successful in C development when coming from a higher level OOP background?

答:
Major differences:

You are responsible for all resource management.  There is no garbage collection, nor are any buffers automatically extended if you need more space. This includes string management.  C does not have a string type as such; strings are stored as arrays of char.  If you want to append strings, you have to make sure the target buffer is large enough before doing so.

There is no structured exception handling.  Errors and exceptional conditions are indicated by function return codes or writing to a parameter (or by setting errno).  You can kind-of-sort-of fake exceptions using the setjmp/longjmp library functions, but it's a hack at best.

C does no bounds checking on array accesses.  There are no built-in exceptions for accessing elements outside of an array. It is ridiculously easy to clobber memory you don't own (as can be seen by innumerable exploits over the years).

Data types are not smart - arrays don't know how big they are (they lose their "array-ness" in most contexts), struct types do not have any sort of methods (you can kind-of-sort-of fake it using function pointers, but there's no implicit this pointer; you explicitly have to tell each function which struct instance to operate on).

Code is organized into modules, rather than classes, where each module consists of type definitions, object definitions, and function definitions.  There's no concept of inheritance between modules.  Visibility for individual data items and functions is an all-or-nothing proposition - there's no equivalent for a "protected" visibility.

There are no container types beyond arrays.  You want anything more sophisticated than that, you will either have to roll your own or find a container library.  Similarly, there are no standard algorithms (such as std::copy or std::foreach - again, you'll have to roll your own).

There are no templates, generics, or other dynamic typing mechanisms.  There's no overloading of functions or operators.  All type information must be known at compile time.

There are no user-definable name spaces.  C supports a grand total of four namespaces - labels, tag names, structure and union member names, and everything else.

It is possible to write OO code in C; it's just a lot of work.

Think of C as a nasty-looking table saw with exposed sharp edges, no blade guards, and visibly frayed wiring, and you'll be in the right mindset.


答:
Many features of the .NET type system, especially the generic types which were added in 2.0 but (from what I understand) anticipated from the get-go, make it literally impossible to compile code for all of the types a program might use before it starts execution (since the combinations of type used by a program may be affected in arbitrary ways by the inputs received by a program, and although the number of discrete types actually used by a program in the course of a single execution must be bounded, the number of types that a program may use in response to various inputs need not be).  While dynamic code generation is possible even without a virtual machine, using a virtual machine makes it much easier and safer.

Further, the efficiency of garbage collection in a multi-threaded environment can be improved tremendously by giving the garbage collector the ability to simultaneously block all threads that might make any use of references to garbage-collected objects.  Even if the garbage collector is required to keep "stop-the-world" events as short as possible, the ability of the collector to unilaterally lock out other threads from interacting with GC references makes it possible for other threads to read and write references without having to use interlocked reads and writes.  This can have enormous effects on efficiency.

Most of what the .NET VM manages to accomplish could be done without using a VM, but using a VM offers huge safety and performance benefits which far outweigh the downsides.

Title: Why is .NET VM based?


问:
Programming Pattern - Single Data Structure - Multiple Methods
I have a single data structure that holds a relatively small amount of objects (ca. 1500) and several methods that are acting on it. Is there a programming pattern to iterate the methods over the data instead of writing significantly more boilerplate code?</p>

答:
I don't think there is a design pattern for this. It's much too simple to be a pattern, I believe.

You have a list of objects and a list of functions, and you want the cartesian product of those two lists, e.g.

```<code>objects := [10, 20, 30]
functions := [add1, subtract1]

product := functions.product(objects)
// product looks like this:
// [(add1, 10), (subtract1, 10), (add1, 20), (subtract1, 20), (add1, 30), (subtract1, 30)]

product.map((fn, o) => fn(o))
// => [11, 9, 21, 19, 31, 29]
</code>```

In C#, it would look a bit like this (I don't really know C#, so take it with a grain of salt):

```<code>using System;
using System.Collections.Generic;
using System.Linq;

class Prog
{
    static int add1(int i) => i + 1;
    static int sub1(int i) => i - 1;

    public static void Main(string[] args) {
        var objs = new List<int> { 10, 20, 30 };
        var funs = new List<Func<int, int>> { add1, sub1 };

        var result =
            from obj in objs
            from fun in funs
            select fun(obj);

        result.ToList().ForEach(Console.WriteLine);
        // 11
        // 9
        // 21
        // 19
        // 31
        // 29
    }
}
</code>```

Body:
I don't think there is a design pattern for this. It's much too simple to be a pattern, I believe.

You have a list of objects and a list of functions, and you want the cartesian product of those two lists, e.g.

objects := [10, 20, 30]
functions := [add1, subtract1]

product := functions.product(objects)
// product looks like this:
// [(add1, 10), (subtract1, 10), (add1, 20), (subtract1, 20), (add1, 30), (subtract1, 30)]

product.map((fn, o) => fn(o))
// => [11, 9, 21, 19, 31, 29]

In C#, it would look a bit like this (I don't really know C#, so take it with a grain of salt):

using System;
using System.Collections.Generic;
using System.Linq;

class Prog
{
    static int add1(int i) => i + 1;
    static int sub1(int i) => i - 1;

    public static void Main(string[] args) {
        var objs = new List<int> { 10, 20, 30 };
        var funs = new List<Func<int, int>> { add1, sub1 };

        var result =
            from obj in objs
            from fun in funs
            select fun(obj);

        result.ToList().ForEach(Console.WriteLine);
        // 11
        // 9
        // 21
        // 19
        // 31
        // 29
    }
}


问:
How to abstract from a display?
I'm building an embedded text editor consisting of a keyboard, an LCD display and a PIC32 microcontroller, to be programmed in C. The application should look, for example, like the GNU nano editor. The display is 40x16 characters big.

I'm currently wondering what would be a good abstraction from the display. We could conceptualise a simple terminal as follows:

```<code>typedef struct {
    char* content;              // Current and past content
    void (*update)(Terminal);   // Update function
} Terminal;
void append(Terminal, char*);   // Append to content & execute update function
void discard(Terminal, int);    // Discard last n characters & execute update f.
</code>```

By adding a function pointer to the Terminal type, we basically have a model and a view. The Terminal can be controlled by the append() and discard() functions. With this Terminal we could make a simple terminal with stdin and stdout.

However, that's not enough for a nano-like editor, where text can be inserted and removed anywhere on the screen, not just at the end of the current data.

I have now made up the following type:

```<code>typedef struct {
    unsigned short rows, columns,     // Screen size
            first_visible_row, first_visible_column,  // Left-top coordinates
            cursor_x, cursor_y;       // Cursor coordinates
    char* content;                    // Current and off-screen content
    void (*update)(Screen);           // Update function
} Screen;
</code>```

This Screen holds off-screen content as well, and its visible section is determined by its left-top coordinates. This makes scrolling easier. But, functions to write to this screen at some position would be complicated, because there is no direct relationship between a position in content and its coordinates on the actual display.

An easier to work with type would hold an array of rows char arrays, for different lines on the screen. Then, content would be an array of char arrays, i.e. char** content.

Basically, I'm asking if there are problems with my suggested approach and if there is an easier approach.

To sum up, here are some of the requirements for the screen:

Should be easy to scroll in

It should be possible to add and remove text at any point on the screen

答:
You might benefit from a double buffer concept where you store lines longer than the display into a larger structure and a zoomed in 40 * 16 array that can move up or down with display events. Provide offset pointers to each start of row and end is determined so arrows move around larger area. Limit shifting to min max. Then cut and paste is line by line segment copy.
Multi line area copies would be the hardest to track, you could limit to window to start.

Buffer area into and out of file is a single write at the end of operations.

Display is a custom per string operation.

Title: How to abstract from a display?


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
You need to give a more specific example, but:

private int count, private int badFileCount, private static readonly int ReconnectAttemptsLimit

By the way, you get all this FREE when you install and start using the latest and greatest MSFT Stylecop.


问:
NodeJS like interrupt handlers?
I got started with programming back in the DOS days. One of my early projects involved overriding the keyboard interrupt service routine with my own. Now I'm trying out NodeJS to update myself, and I feel there is a similarity between the non-blocking design of NodeJS and my old experience with interrupt service routines (ISR). My guess is the similarity would be the keyboard ISR would wait for a key press input signal from the keyboard, while NodeJS waits for a web request. When the input arrives, both NodeJS and the ISR need to hurry to handle the request and say they're done in case a new input arrives. That is, there is a penalty for a CPU bound task slowing down the next web response or the next keyboard key input. Is this observation a reasonable understanding?  I'm new to NodeJS so perhaps I'm missing an important difference or just incorrect in some fundamental way.</p>

答:
Sort of.

Interrupt Service Routines are really just hardware hooks so that the keyboard or other hardware device can make a subroutine call to the operating system while maintaining a degree of isolation.  There's a lot more to it, of course, and if the method appears to be asynchronous, it's only because operating systems back then were capable of rudimentary task switching, or maybe even cooperative multitasking.

Node.JS's mechanism of operation is a bit different.  Node.JS has an event loop that receives requests, each of which it assigns to a new thread under the covers.  An async handler is registered to receive the eventual result of the requests.  Everything happens at a much higher level of abstraction.

Title: NodeJS like interrupt handlers?


问:
Computer Algorithms for Polynomial Regression
Given a data set of arbitrary size, what algorithm would be appropriate for performing the polynomial regression on the data set such that the highest degree of the polynomial is n? If there are multiple of such algorithms, what is more efficient for particular data sets (other then the obvious line fitting the data set according to its shape--or not)?</p>

答:
If you have decided in advance to allow polynomials with degree at most n, then "regression on the data set" amounts to finding a best-fit polynomial with that restriction.  Avoid "over-fitting" the data set, by choosing a degree n higher than is justified by the extent and quality of data points.

The most common approach is a least-squares fit, minimizing the sum of squares of errors at the data points.  The solution is found by solving a linear system of equations for the polynomial coefficients. Line-fitting (where one independent variable is present) entails solving a system of two equations for the slope and intercept (constant term).

Two other methods are minimizing the sum of absolute errors and minimizing the maximum absolute error (at any data point).  These methods have solutions that can be obtained by linear programming algorithms.

Each of these methods has a variation in which relative errors (proportions of nonzero data) rather than absolute errors are used.  More generally nonnegative weights may be assigned a priori to the data points in order to represent higher confidence in some data points (measurements) than in others.

The choice of method should be based on the quality of the data (how much variance do the errors exhibit) and on the time constraints for finding a solution.  Since the solution is an approximation to data containing errors, the pursuit of a highly accurate solution to the approximation problem may quickly turn into a diminishing returns effort.


问:
Understanding a project architecture
If I develop an application, I'll often use a project structure like this:

```<code>MyApp.DataAccess.Implementation
MyApp.DataAccess.Contract
MyApp.Business.Implementation
MyApp.Business.Contract
MyApp.CrossCutting.Implementation
MyApp.CrossCutting.Contract
MyApp.Application
</code>```

For each layer I'll create two assemblies. One for the interfaces and one for the implementation itself. In the layer "CrossCutting" is everything like logging, entities, configuration... If the project is really big, I'll separate each component in the "CrossCutting" layer into a separate assembly. In the application layer, there's my console/ui/web project.

This project structure can be applied easy on bigger projects. But for small project I think that this is oversized. So, after some time searching with google, I found a simple structure for smaller projects.

```<code>Core
Data
Domain (or BusinessObjects)
Services
Utilities (or Helpers)
</code>```

My problem with this structure is, I've no Idea what these layers represent. Can someone explain me these layers?

答:
Three-tier architecture Wikipedia article already explains two of them:

Data access layer (DAL) is what contains the logic directly bound to the data. For instance, if your application uses Oracle database and later, you migrate to MongoDB, the data access layer is the only layer you are expected to rewrite.

The goal of this layer is to abstract the access to the underlying data source for the business layer. For instance, it may load data from multiple tables and aggregate it before presenting a convenient to use result to the business layer. Another example is that the DAL can manage concurrency control, that is check that an entity changed by somebody else while a user was changing it.

Business layer (BL) is what (usually) contains the most important part of your application: the actual business logic, the reason why this application exists in the first place.

For instance, you'll find here the accounting rules or rules processor if you deal with an application for accountants, or the actual calculus if you deal with scientific application.

Three-tier architecture also contains a third layer:

Presentation layer (PL), the one which deals with presenting the information to the user (in a case of an end-user application) or the caller (in a case of a web service), and, inversely, processing (which also means sanitizing) the input.

As for the other layers listed in your question:

Core contains the framework developed specifically for your project. For example, if you're writing a web application, you may extend the existent web framework with functionality you'll need in this specific project, such as a fancy URL rewriting or the part which loads application configuration.

Services is like DAL, but for different services. For instance, if you are using Google APIs, you may put all the logic which makes the actual calls to Google servers in this layer.

Similarly to the DAL, it makes it possible to switch easily between the service providers; for instance, switch from Google Maps API to Bing Maps API.

Utilities contains the utility methods. Make sure you read this and that to understand why utility methods should be avoided if you care about OOP.

Title: Understanding a project architecture


问:
Best approach for managing users that are defined inside the active directory, inside my custom application
I want to start a new asp.net mvc5 Personal Appraisals web project. Now I will have a module inside the system for managing users, and adding info such as primary role, secondary role, main skills, rating for each skill.

As the users are already inside the active directory so I do not want to store duplicate info such as their first name, last name, email address, I want to retrieve them directly from the AD. So I am thinking of this scenario:

Click on "Add user".

Start typing first name, where the system will auto-complete the related users from AD.

Select specific user. The system will populate its first and last names + email address.

Enter info such as primary role, main skills, etc.

Save

After that I will ONLY save the GUID for the user or any id that uniquely identify the user inside the AD.

Later on when I want to view the users info, I will dynamically retrieve his first name, last name, and email address from the AD based on the GUID id which i store inside my DB, and display them inside my system + the info which is stored inside my DB (such as primary role, skills, etc).

So can anyone advise on this approach, or is it better to store the users' info inside my system, and define a sync job which will synchronize the users as defined inside the AD?  I'm not sure how I should be handling this scenario.
Thanks.

答:
Its a slightly confused message from Microsoft. One the one hand, storing custom schemas in AD seems an ideal place to put it, but on the other hand they don't want you to do it. AD guides note that while you can add schemas to AD, you can never remove them afterwards. This makes Admins nervous. I wouldn't want to have a central user audth system that ends up growing with extraneous data you could never prune or tidy up if you stop using the application that required it.

What they have produced is an AD-lite system (called ADAM) that you can link to your AD so AD holds the users, and ADAM holds the custom data. I never quite got it to work, the tooling to manage the system is poor, and even if you do put your custom data in it you have to jump through a lot of hoops to make it accessible to the AD admins (which is the point of putting it in there - single point of administration of user data)

I would strongly recommend using a normal database to hold your custom data. Put a primary key that corresponds to the user's GUID and read your data in 2 phases, read/authenticate the user, and then use the user GUID to read the custom data from your DB as normal.


问:
Motivating yourself to actually write the code after you've designed something
Does it happen only to me or is this familiar to you too?

It's like this: You have to create something; a module, a feature, an entire application... whatever. It is something interesting that you have never done before, it is challenging.

So you start to think how you are going to do it. You draw some sketches. You write some prototypes to test your ideas. You are putting different pieces together to get the complete view.

You finally end up with a design that you like, something that is simple, clear to everybody, easy maintainable... you name it. You covered every base, you thought of everything. You know that you are going to have this class and that file and that database schema. Configure this here, adapt this other thingy there etc.

But now, after everything is settled, you have to sit down and actually write the code for it. And is not challenging anymore.... Been there, done that! Writing the code now is just "formalities" and makes it look like re-iterating what you've just finished.

At my previous job I sometimes got away with it because someone else did the coding based on my specifications, but at my new gig I'm in charge of the entire process so I have to do this too ('cause I get payed to do it).

But I have a pet project I'm working on at home, after work and there is just me and no one is paying me to do it. I do the creative work and then when time comes to write it down I just don't feel like it (lets browse the web a little, see what's new on P.SE, on SO etc).

I just want to move to the next challenging thing, and then to the next, and the next...

Does this happen to you too? How do you deal with it?

How do you convince yourself to go in and write the freaking code?

I'll take any answer.

答:
It's definitely not just you! I'm actually putting a project off right now.

Nobody can motivate you but yourself.

Create a realistic time-line and challenge yourself to complete each section on time. You have nothing to show for projects if they never get passed the design phase.


答:
I can definitely relate to that.  I love taking on the challenge of things I haven't encountered, but I have a hard time starting working on anything that I have already solved.  The biggest thing I do is just force myself to sit down with a goal of getting X done and functioning.  Usually once I get going I end up having fun and get more than done than I set out in the first place, but if I don't force a goal, ill just drft for hours.

I'm also with you in that this happens more at home on sidework than in the office.  I don't know if its more distractions, being burnt from work or what...

Title: Motivating yourself to actually write the code after you've designed something

Body:
Does it happen only to me or is this familiar to you too?

It's like this: You have to create something; a module, a feature, an entire application... whatever. It is something interesting that you have never done before, it is challenging.

So you start to think how you are going to do it. You draw some sketches. You write some prototypes to test your ideas. You are putting different pieces together to get the complete view.

You finally end up with a design that you like, something that is simple, clear to everybody, easy maintainable... you name it. You covered every base, you thought of everything. You know that you are going to have this class and that file and that database schema. Configure this here, adapt this other thingy there etc.

But now, after everything is settled, you have to sit down and actually write the code for it. And is not challenging anymore.... Been there, done that! Writing the code now is just "formalities" and makes it look like re-iterating what you've just finished.

At my previous job I sometimes got away with it because someone else did the coding based on my specifications, but at my new gig I'm in charge of the entire process so I have to do this too ('cause I get payed to do it).

But I have a pet project I'm working on at home, after work and there is just me and no one is paying me to do it. I do the creative work and then when time comes to write it down I just don't feel like it (lets browse the web a little, see what's new on P.SE, on SO etc).

I just want to move to the next challenging thing, and then to the next, and the next...

Does this happen to you too? How do you deal with it?

How do you convince yourself to go in and write the freaking code?

I'll take any answer.


问:
Justifying programmatically ensuring frontend and backend validations are synchronised
Like many Javascript-based rich web apps these days, I have some complicated validation rules implemented on the front-end. The same rules are supposedly repeated exactly on the Java backend but I always find small deviations.

As a believer of the DRY principle, I think something should be done to systematically fix this. Ideally both sides should run the same code and use the same rules, but since running JavaScript on the backend is not allowed, I can only hope to reuse some meta-fied validation rules. Fortunately, I found some library on GitHub that can do this for JSR-303 annotation-based validation. However, a lot of rewriting and refactoring is still required.

On the other hand, the number of rules is limited (< 80 in total) and the current code is clear and simple to understand (just a bunch of if statements). Using a validation framework would require all custom validators to be wrapped and hidden behind generated meta-data not immediately visible during development, so loads of additional learning curve.

It seems my goal to improve the code will really just harms maintainability. What's people's experience on this?

答:
You could use some rule-based DSL to specify the validation rules used by both the front and back ends. This though then requires code on both the front and back ends to read and implement those validation rules. This leads to the problems that the validation rule reading and implementing code has to be written twice. This can still lead to inconsistencies, and it adds to the size of your code base, increasing its complexity.

The way to reduce code complexity and the risks of inconsistent rule checking is to offload all validation to the server side. The JavaScript code then uses AJAX calls to request the back end validate the input. The front end knows nothing about the validation rules, it simply gets told whether the input is valid or not.


答:
In my experience the validations on client and server often differ for good reason.

Generally a server side, low level process will throw an exception, with perhaps a short description, maybe an error number. This is meant for logging to an error log rather than showing to an end user.

While a client side error is processed prior to making a call and will present the user with a descriptive error message, in their own language, perhaps with UI elements highlighting the problem.

this leads to a difference in both the way the validation is done, the error message returned and otfen the actual logic of the validation.

for example take my favorite example, the long form presented as a 'wizard' set of short forms with validation at each step. The Validation of the user input is going to be split up and done at each stage. Where as the server side logic will be expecting all the data at once.

Title: Justifying programmatically ensuring frontend and backend validations are synchronised

Body:
Like many Javascript-based rich web apps these days, I have some complicated validation rules implemented on the front-end. The same rules are supposedly repeated exactly on the Java backend but I always find small deviations.

As a believer of the DRY principle, I think something should be done to systematically fix this. Ideally both sides should run the same code and use the same rules, but since running JavaScript on the backend is not allowed, I can only hope to reuse some meta-fied validation rules. Fortunately, I found some library on GitHub that can do this for JSR-303 annotation-based validation. However, a lot of rewriting and refactoring is still required.

On the other hand, the number of rules is limited (< 80 in total) and the current code is clear and simple to understand (just a bunch of if statements). Using a validation framework would require all custom validators to be wrapped and hidden behind generated meta-data not immediately visible during development, so loads of additional learning curve.

It seems my goal to improve the code will really just harms maintainability. What's people's experience on this?


答:
I do certainly understand your frustration as I've been through it myself before.

Despite fearing some flames from the community as I know this isn't a great approach, I'll share my approach for side projects with you. Please note that this method works for me and I use it on medium/long term projects, I wouldn't do it for something small (as I usually have the motivation to finish it in one go).

Grab the whole project and break it into 'packages', each one consisting of parts that are going to interact with each other often. Then divide each package into small pieces (think a few hours max) that you can design and code.

Ideally you'd be able to complete each piece in whatever time you allocate for your side project for a day but that's not required (depends on the person).

Personally, I don't set myself up with an estimated timeframe for each piece because I just get dissapointed and demotivated once I fail that estimate, hence, I do not recommend that. Take your time but don't take too long either.

Now each small piece gets all of the stages in your normal development process, designing, testing, implementation and whatever else you need to do. The idea is to give each piece a good kick-start but not a full blown finishing touch, yet.

This keeps my motivation up because I know that after a couple hours of actual coding boring stuff I'll have more designing to do (yummy). Don't let yourself stray from your goals, just keep doing that dreadful task and it'll soon be over and done with.

After you've been through all of the pieces, look at the package. See how it works, what's it doing, review the whole package again. I'm sure there will be changes and tweaks, do those now. Keep the most vital information in your mind as you will need it when working on all the other packages. Keep notes too, they help a lot.

Go through each package and keep remembering all the others you did before, how is the new code you're writing going to interact with stuff you wrote a week ago? Don't be afraid to lookup stuff you've already written and maybe forgot.

Finally, when you're all out of packages, I usually let it go for a few days, give myself a rest and focus on something else.

Normally I'm itching to go back and start interwining the packages and do some playful testing, there's not that much more code to write and the goal is near, that's motivation enough for me then.

Hope this helps you with your endeavours.