答:
If there are a lot of heavy shared functions, I would move as much as possible of the implementation into a REST-based web service. Then all the library assemblies could be made into light-weight wrappers using the built-in .NET libraries only.

If you can get away from client-api dll distribution (eg: bloomberg), and keep them in one place, it makes it much easier to swap them out or replace them in the future.

Title: Two libraries connecting to the database, leading to code smell?

Body:
In the current company that I work for there is a very large Utilities library. It was written a few years back (long before I joined) and has grown ergonomically over time to now do everything:

Sending Emails

Exporting Files in different formats, i.e. CSV, tab delimited

Receiving data from 3rd party providers, i.e. Bloomberg, Facset

Sending files to SFTP sites

Generic database connection

The list goes on and it is pretty ugly really.

The original developer here used it in every application that he wrote for convenience sake and added to it as necessary. The utilities library itself has references to 3rd party API’s to do some data receiving from Bloomberg/Factset. Using these 3rd party API’s means that any project that wants to reference the large Utilities library also then needs to have the Bloomberg API’s and Facset API’s with it. The list is starting to grow too and it is becoming very unmaintainable and unnecessary to have all these 3rd party DLL’s accompanied with this large Utilities project but are required to compile it.

I want to rewrite this entire library it to more manageable libraries. i.e:

CompanyName.Email

CompanyName.FileExporter

CompanyName.Bloomberg

Each project will then only reference the necessary projects it needs to get its job done. i.e. reference the CompanyName.Email to send emails.
I have no issues doing that, but the complication facing me is that some of the new libraries will require their own database connection and queries.
The example below is:

```<code>[HolidayChecker]
[HolidayChecker.DAL]
</code>```

We store a list of holiday days in the database. What I would want the HolidayChecker project to do is expose a method (amongst others) to check if a particular date is a holiday.

```<code>public interface IHolidayChecker
{
    bool IsHoliday(DateTime dateToCheck);
}
public class HolidayChecker : IHolidayChecker
{
    public bool IsHoliday(DateTime dateToCheck)
    {
        //Query database for date logic...
    }
}
</code>```

Many applications will then reference this HolidayChecker project and use the IsHoliday method. These applications will also have their own connection and queries to the database to perform their own tasks.

```<code>[GenericApplication (References HolidayChecker)]
[GenericApplication.BusinessLogic]
[GenericApplication.DAL]
</code>```

If the application and the HolidayChecker project both access the database and query the data, this comes across heavily as code smell. Is anyone aware of a tidier way of achieving this? Or is there? Is this something I will just have to live with?

EDIT:

Thinking about this overnight, I don't think it is a bad as first thought. Projects like ELMAH are stand alone that also connect to the database and do their own queries. As @Allan pointed out, it is just a matter of designing my HolidayChecker project correctly.


问:
Describe the best deployment environment you've worked with
The Joel Test includes the question:

Can you make a build in one step?

Which is important, but I'm wondering, how streamlined have some of the deployment processes been?

All software from shrink-wrap to web applies: what's the best deployment environment you've worked with, and what steps were involved?

答: Not for nothing, but right-clicking on an ASP.NET web app and selecting Publish was a nice, pleasant surprise when I had to deploy an app. Granted, I had to set up the virtual directory and such on IIS beforehand, but deploying new versions is a few clicks away.</p>

ContentLicense: CC BY-SA 2.5


问:
Is there a specific name for the "Square inherits from Rectangle" paradox?
A certain failure of OOP is shown with a class Square inheriting from Rectangle, where logically Square is a specialization of Rectangle and should therefore inherit from it, but everything falls apart when you attempt to change a Square's length or width.

Is there a specific term for describing what is going wrong with that case?

答:
Wikipedia merely refers to it as the Circle-ellipse problem

The circle-ellipse problem in software development (sometimes known as the square-rectangle problem) illustrates a number of pitfalls which can arise when using subtype polymorphism in object modelling. The issues are most commonly encountered when using object-oriented programming.

This is the L in the acronym S.O.L.I.D. which is known as the Liskov substitution principle. This problem arises as a violation of that principle.

The problem concerns which subtyping or inheritance relationship should exist between classes which represent circles and ellipses (or, similarly, squares and rectangles). More generally, the problem illustrates the difficulties which can occur when a base class contains methods which mutate an object in a manner which might invalidate a (stronger) invariant found in a derived class, causing the Liskov substitution principle to be violated...

ContentLicense: CC BY-SA 3.0


问:
Two libraries connecting to the database, leading to code smell?
In the current company that I work for there is a very large Utilities library. It was written a few years back (long before I joined) and has grown ergonomically over time to now do everything:

Sending Emails

Exporting Files in different formats, i.e. CSV, tab delimited

Receiving data from 3rd party providers, i.e. Bloomberg, Facset

Sending files to SFTP sites

Generic database connection

The list goes on and it is pretty ugly really.

The original developer here used it in every application that he wrote for convenience sake and added to it as necessary. The utilities library itself has references to 3rd party API’s to do some data receiving from Bloomberg/Factset. Using these 3rd party API’s means that any project that wants to reference the large Utilities library also then needs to have the Bloomberg API’s and Facset API’s with it. The list is starting to grow too and it is becoming very unmaintainable and unnecessary to have all these 3rd party DLL’s accompanied with this large Utilities project but are required to compile it.

I want to rewrite this entire library it to more manageable libraries. i.e:

CompanyName.Email

CompanyName.FileExporter

CompanyName.Bloomberg

Each project will then only reference the necessary projects it needs to get its job done. i.e. reference the CompanyName.Email to send emails.
I have no issues doing that, but the complication facing me is that some of the new libraries will require their own database connection and queries.
The example below is:

```<code>[HolidayChecker]
[HolidayChecker.DAL]
</code>```

We store a list of holiday days in the database. What I would want the HolidayChecker project to do is expose a method (amongst others) to check if a particular date is a holiday.

```<code>public interface IHolidayChecker
{
    bool IsHoliday(DateTime dateToCheck);
}
public class HolidayChecker : IHolidayChecker
{
    public bool IsHoliday(DateTime dateToCheck)
    {
        //Query database for date logic...
    }
}
</code>```

Many applications will then reference this HolidayChecker project and use the IsHoliday method. These applications will also have their own connection and queries to the database to perform their own tasks.

```<code>[GenericApplication (References HolidayChecker)]
[GenericApplication.BusinessLogic]
[GenericApplication.DAL]
</code>```

If the application and the HolidayChecker project both access the database and query the data, this comes across heavily as code smell. Is anyone aware of a tidier way of achieving this? Or is there? Is this something I will just have to live with?

EDIT:

Thinking about this overnight, I don't think it is a bad as first thought. Projects like ELMAH are stand alone that also connect to the database and do their own queries. As @Allan pointed out, it is just a matter of designing my HolidayChecker project correctly.

答:
Wait. Do you have an issue in the first place? What are you trying to solve?

Too large

You say you have a library which is too large. What does it mean? It may mean that:

The binary is just so huge that it's hardly possible to distribute it. Nobody wants to include (and so distribute) a 100 MB DLL file in order to use only few of the methods.

Is this your case? How much space does it takes? 100 MB? 1 GB? I've rarely seen .NET libraries larger than a few megabytes. Given actual average connection speeds, price by GB of memory and disk space, etc., one megabyte more or less doesn't matter, and obviously doesn't worth wasting days, weeks or months of your time.

The library contains so many methods that you can't find the one you need.

This is not the problem of size, but rather the issue with the organization. Create additional namespaces, if OOP wasn't understood by your predecessor — refactor heavily, but don't split a large library into multiple smaller ones just because the code is a mess: it probably won't solve the problem.

Too dependent

You say any project which references the utilities library should also reference the different APIs. How those APIs are implemented? What makes it mandatory to reference them? In ordinary cases, in .NET Framework, when project A references project B which references project C, A should reference C if and only if A uses C through B. So to solve this particular problem, just fix the way those APIs are referenced.

Too slow?

You might also say that a large library is slower to load. Don't. Use a profiler, gather metrics, and if and only if those metrics show that there is a huge gap between loading a 1 MB library or loading, say, four 150 KB libraries, you may optimize. Without precise profiler results, talks about performance remain pure speculation.

So, one library for everything?

There are reasons to split a large library into several smaller ones.

Compile times.

On a not-very-fast PC, a large library will take too long to build. If you're actively working on one part of the library, while other parts remain pretty stable, it may be annoying to be forced to rebuild everything at every change. Putting the code you're working on into a dedicated library may render the local compilation faster.

I know, compiling a library, even a large one, is pretty fast on any decent configuration. Agreed, but what about Code contracts, for example? On my machine, a project may compile within a few seconds, then take minutes to do the static checking (even with caching enabled, very surprisingly). Smaller library means faster results, meaning shorter cycles.

Security.

Redistributing a library means it may be subject to reverse engineering. If this is a concern, less code you give, less is the risk for it to be stolen and reused.

Layers.

You may need to be sure that some parts of the library are not using other parts. For example, in an ordinary web application, the data access layer is not expected to use presentation layer.

To enforce those rules, you'll ordinarily use Layer Diagram in Visual Studio, specifying which libraries can reference which others. If all the code is in one library, there is no easy way to check automatically that a part of the library is not using another one.

Frequent updates.

If the library is referenced by an application which is used by hundreds of thousands of persons and the project is updated nearly every day, reducing the library by 100 KB means saving 20 GB of bandwidth daily, which is not so bad.

Conclusion

No, a large library is not a code smell and has nothing to do with code smells. It may have some drawbacks, but only in a few particular circumstances.

I would be more concerned if there were, say, fifty small libraries. It's difficult to organize, it's difficult to deal with, and more importantly, developers would be less inclined to move code from a library to another rather than from a namespace to another, which would sooner or later lead to duplication of code.


问:
What is the preferred access modifier for instance variables of a data transfer object?
I'm creating a data transfer object and can't decide whether it would be better to just give public access to the instance variables or if there would be a purpose to using getters and setters to access the data?

According to the Data transfer object Wikipedia Article:

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

It seems that public access would be justified for a DTO's instance variables.

Here is the example I'm working on:

Ivars with public access modifier:

```<code>class ServerContext
{
    public String host;
    public String user;
    public String password;
    public int port;

    ServerContext(String host, String user, String password, int port) {
        this.host = host;
        this.user = user;
        this.password = password;
        this.port = port;
    }
}
</code>```

vs.
private access modifiers:

```<code>class ServerContext
{
    private String host;
    private String user;
    private String password;
    private int port;

    ServerContext(String host, String user, String password, int port) {
        setHost(host);
        setUser(user);
        setPassword(password);
        setPort(port);
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
</code>```

EDIT: Could these be valid arguments for keeping the ivars private:

The potential of refactoring a DTO later to have more functionality?

Wanting to keep implementation consistent between DTO and regular
    objects?

答:
It depends a bit how these object will be used, normally public visibility would be enough (or  how they are called in modern languages - properties), but because it's java, you can have frameworks, where you should have methods to get and set values (setAttribute(), getAttribute() ).
If you don't use any framework where you need to have special methods to access object members, I would say use public fields. Of course if you need to write more code lines, then generating extra code for set/get values is better for you.</p>


问:
Is repeating links to the same class in a single javadoc comment a bad practice?
I'm currently writing an API and its documentation. For example I have something like this:

```<code>public interface Event {
}

public interface Process {
}

public interface EventProcessor {
    /**
     * Starts to process the sepcified event asynchronously. The returned
     * {@link Process} can be used to track progress on the processing. If the
     * specified event causes more {@link Event events} to be processed in this
     * system, then they are also tracked via the returned {@link Process}.
     *
     * @param event
     *            to be started to process
     * @return
     */
    Process startProcessing(Event event);
}
</code>```

In the example above, the javadoc link to the interface Process is repeated. In the API I'm writing there are cases where I have several more references to the same class in a single javadoc comment.

Should I always mark references to the class/method/etc. as javadoc links?

Generally, I think having many links in a javadoc comment is a sign for high cohesion. But when it's often the same target, which is linked, I'm not sure if this is good.

答:
I hate to be the one to tell you, but if you really (really) worry about repeating then it's irrelevant how many links will be there because no matter what, readers of generated javadocs will see text repeated twice:

...returned Process can be used to track progress on the processing. If the specified event causes more events to be processed in this system, then they are also tracked via the returned Process

So, prior to making complicated decisions to link or not to link, you better decide on basics: would you worry about repeating text or not?

If you decide not to worry about repeating text, then it really makes better sense not to worry about links - just use them the way that feels easier to you. Readers watching repeated text are unlikely to appreciate your efforts about consistency in presenting links in it.

If, on the other hand, you decide to rephrase docs to avoid repeating text, this will also resolve your concern about repeating links.

Just be careful here, because making good, easy to read, non-repetitive text may take quite a lot of effort. In that case, consider involving someone else to review your docs (generated, because these will look different from javadocs sources).

If you don't have a luxury of a reviewer, do self-reviews, that is wait for a day or two (better for a week or two), then review the docs yourself - fresh look will be almost (though not quite) like another pair of eyes.


问:
Issues to be considered while loading jQuery?

I have seen many answers in SO regarding using Google's CDN to load jQuery instead of

loading it from the local server. In essence I understand this is the issue related with decreased latency, better caching. But I want to know the technical answer, perhaps an example mentioning why it is even an issue to just load a 30KB file. We see nowadays websites with rich multimedia features which do significant download from server, so in such light does this file size make any difference?

Also there are huge concerns regarding using such "heavy weight" library if all you are using is just a fraction of subset of features? And if you are going to use at all, it is recommended to use compressed version (30+ KB) instead of the uncompressed one(200+ KB)? I also know the usual answers to it, perhaps if someone can shed more insight to it?

My both questions mentioned above are essentially trying to raise the same issue. I would be very grateful for answers that can provide the perspective to it rather than usual answers in SO?

答:
AND another point!

As shown in some performance talks about Javascript, many browsers will basically stop loading anything while they are loading and running a Javascript file - essentially, they can't be sure if this script will change the way future objects are loaded, or especially the way future scripts are run. So, while a number of images could be downloaded at once, script files tend to block execution, and so their load time is especially important. (Note this is not the case when the newer HTML tag async is specified)


问:
In languages that don't allow underscores in integer constants, is it a good practice to create a constant for 1 billion?
In languages that don't allow underscores in integer literals, is it a good idea to create a constant for 1 billion?  e.g. in C++:

```<code>size_t ONE_BILLION = 1000000000;
</code>```

Certainly, we shouldn't create constants for small numbers like 100.  But with 9 zeros, it's arguably easy to leave off a zero or add an extra one in code like this:

```<code>tv_sec = timeInNanosec / 1000000000;
tv_nsec = timeInNanosec % 1000000000;
</code>```

答:
The length of the value is not what defines whether a constant is needed or not.

You use constants to avoid magic numbers, not to avoid typing.

For example these are perfectly valid constants:

```<code>public static final int CLOSE_CURSORS_AT_COMMIT = 1;
public static final int CONCUR_READ_ONLY = 2;
public static final int CONCUR_UPDATABLE = 3;
public static final int FETCH_FORWARD = 4;
public static final int FETCH_REVERSE = 5;
public static final int FETCH_UNKNOWN = 6;
public static final int HOLD_CURSORS_OVER_COMMIT = 7;
public static final int TYPE_FORWARD_ONLY = 8;
public static final int TYPE_SCROLL_INSENSITIVE = 9;
public static final int TYPE_SCROLL_SENSITIVE = 10;
</code>```

Use:

```<code>public static final int NANOSECS_PER_SECOND = 1000000000;
</code>```

(code samples are in Java, translate to your favorite language )

Body:
The length of the value is not what defines whether a constant is needed or not.

You use constants to avoid magic numbers, not to avoid typing.

For example these are perfectly valid constants:

public static final int CLOSE_CURSORS_AT_COMMIT = 1;
public static final int CONCUR_READ_ONLY = 2;
public static final int CONCUR_UPDATABLE = 3;
public static final int FETCH_FORWARD = 4;
public static final int FETCH_REVERSE = 5;
public static final int FETCH_UNKNOWN = 6;
public static final int HOLD_CURSORS_OVER_COMMIT = 7;
public static final int TYPE_FORWARD_ONLY = 8;
public static final int TYPE_SCROLL_INSENSITIVE = 9;
public static final int TYPE_SCROLL_SENSITIVE = 10;

Use:

public static final int NANOSECS_PER_SECOND = 1000000000;

(code samples are in Java, translate to your favorite language )


答: I would consider it a violation of the Liskov Substitution Principle - the Square subclass specifically violates the invariant that length and width are independent.

Title: Is there a specific name for the "Square inherits from Rectangle" paradox?

Body:
A certain failure of OOP is shown with a class Square inheriting from Rectangle, where logically Square is a specialization of Rectangle and should therefore inherit from it, but everything falls apart when you attempt to change a Square's length or width.

Is there a specific term for describing what is going wrong with that case?


答:
In layman's words.

Public instance variables violate encapsulation.

In doing so, client code will be coupled to the names of your instance variables.

Client code should not be coupled to anything internal.

Internal things could change in the future.

External interface ( contract ) should not be affected by changed internals.

If you don't want to manually write your getters and setters let the IDE do it for you.

Also, getters and setters lets you use the builder pattern to construct and "build" an instance of your object without the hundred-parameter constructor.

The class having no-behavior doesn't mean you can violate encapsulation. It also doesn't mean it will never have behavior in the future.

Title: What is the preferred access modifier for instance variables of a data transfer object?

Body:
I'm creating a data transfer object and can't decide whether it would be better to just give public access to the instance variables or if there would be a purpose to using getters and setters to access the data?

According to the Data transfer object Wikipedia Article:

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

It seems that public access would be justified for a DTO's instance variables.

Here is the example I'm working on:

Ivars with public access modifier:

```<code>class ServerContext
{
    public String host;
    public String user;
    public String password;
    public int port;

    ServerContext(String host, String user, String password, int port) {
        this.host = host;
        this.user = user;
        this.password = password;
        this.port = port;
    }
}
</code>```

vs.
private access modifiers:

```<code>class ServerContext
{
    private String host;
    private String user;
    private String password;
    private int port;

    ServerContext(String host, String user, String password, int port) {
        setHost(host);
        setUser(user);
        setPassword(password);
        setPort(port);
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
</code>```

EDIT: Could these be valid arguments for keeping the ivars private:

The potential of refactoring a DTO later to have more functionality?

Wanting to keep implementation consistent between DTO and regular
    objects?


问:
What can I use to keep track of the status of 60 programs, some of which are obsolete?
I've taken a software development role in an engineering company(all software developed is for internal use only). The company has about 60 individual programs from past developers.  The problem is that all past developers are gone and no one knows why about half of the software was built, who uses it, or even what some of it does.  We use SVN, but no past developers wrote comments or did any sort of documentation.

Assuming I figure all of this out, is there some program/system/method that could be used to keep track of all this information?  The company is leaning toward Excel, I'm assuming there's something better.  Would it just be better to write up documentation in a Word Doc and commit it to svn so it's right next to the code?

答: Instead of a simple spreadsheet or text file, I'd suggest something like TiddlyWiki.  It's a simple wiki that runs entirely within a browser, so there's nothing to install or configure.  Stick it in a public location and periodically back it up (just commit the file to a Subversion repo).  It'll provide a bit of structure without (hopefully) being too limiting.  If you need something more, Liferay offers an open-source portal-based "collaboration management" tool.  I've used it on a couple of projects, but it's probably overkill for what you're trying to do.</p>


答:
An American or European billion?

(or in technical terms, a billion in the short scale or long scale - one is 1000 million, the other is a million million).

Given this confusion, then I'd say yes - it makes sense to define it once and keep with it, likewise applies to any constant you need to agree the definition on - define it once.

Title: In languages that don't allow underscores in integer constants, is it a good practice to create a constant for 1 billion?

Body:
In languages that don't allow underscores in integer literals, is it a good idea to create a constant for 1 billion?  e.g. in C++:

```<code>size_t ONE_BILLION = 1000000000;
</code>```

Certainly, we shouldn't create constants for small numbers like 100.  But with 9 zeros, it's arguably easy to leave off a zero or add an extra one in code like this:

```<code>tv_sec = timeInNanosec / 1000000000;
tv_nsec = timeInNanosec % 1000000000;
</code>```


问:
Strengthening code with possibly useless exception handling
Is it a good practice to implement useless exception handling, just in case another part of the code is not coded correctly?

Basic example

A simple one, so I don't loose everybody :).

Let's say I'm writing an app that will display a person's information (name, address, etc.), the data being extracted from a database. Let's say I'm the one coding the UI part, and someone else is writing the DB query code.

Now imagine that the specifications of your app say that if the person's information is incomplete (let's say, the name is missing in the database), the person coding the query should handle this by returning "NA" for the missing field.

What if the query is poorly coded and doesn't handle this case? What if the guy who wrote the query handles you an incomplete result, and when you try to display the informations, everything crashes, because your code isn't prepared to display empty stuff?

This example is very basic. I believe most of you will say "it's not your problem, you're not responsible for this crash". But, it's still your part of the code which is crashing.

Another example

Let's say now I'm the one writing the query. The specifications don't say the same as above, but that the guy writing the "insert" query should make sure all the fields are complete when adding a person to the database to avoid inserting incomplete information. Should I protect my "select" query to make sure I give the UI guy complete informations?

The questions

What if the specifications don't explicitly say "this guy is the one in charge of handling this situation"? What if a third person implements another query (similar to the first one, but on another DB) and uses your UI code to display it, but doesn't handle this case in his code?

Should I do what's necessary to prevent a possible crash, even if I'm not the one supposed to handle the bad case?

I'm not looking for an answer like "(s)he's the one responsible for the crash", as I'm not solving a conflict here, I'd like to know, should I protect my code against situations it's not my responsibility to handle? Here, a simple "if empty do something" would suffice.

In general, this question tackles redundant exception handling. I'm asking it because when I work alone on a project, I may code 2-3 times a similar exception handling in successive functions, "just in case" I did something wrong and let a bad case come through.

答:
In layman's words.

There is no such a thing as "the database" or "the application".

A database can be used by more than one application.

An application can use more than one database.

The database model should enforce data integrity, that includes    throwing an error when a a required field is not included in an    insert operation, unless a default value is defined in the table definition. This must be done even if you     insert the row directly into the database bypassing the app. Let the database system do it for you.

Databases should guard data integrity and throw errors.

Business logic must catch those errors and throw exceptions to the    presentation layer.

Presentation layer must validate input, handle exceptions or show a sad hamster to user.

Again:

Database->throw errors

Business Logic->catch errors and throw
exceptions

Presentation Layer->validate, throw exceptions or show sad
messages.


答:
I'm creating a data transfer object and can't decide whether it would be better to just give public access to the instance variables or if there would be a purpose to using getters and setters to access the data?

Properties can only be renamed. Get/set methods can be deprecated, validation rules applied and coded to convert data to different types. If you don't need those things then don't waste time.

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

Property set/get methods aren't behavior or business logic. They are just access methods to control the scope and access to interval states. A class would still be a DTO with get/set methods.

It seems that public access would be justified for a DTO's instance variables.

If public access to properties was a bad thing. Java wouldn't have the public keyword for properties. If the object works fine with code having read/write access to properties, then why add a ton of get/set methods with one line of code.

If on the other hand you need read-only, then create get methods.


问:
Looking for good practices on managing branches and developers in Git
I a little while ago I joined a new development team and recently we had our first major release. We've used Git since the beginning of the project and by now are somewhat comfortable with it. However, now that the product is in the field, we are discovering new issues/processes that need to be established. Up to this point, everything we've done was by referencing the very popular successful branching model post, which indeed has been very helpful

Currently we have the following branches, all live and all being updated:

master - only released, stable code (tagged every time release is cut)

develop - wide open. used for long term development

hotfix-1.0.1 - branched off master's 1.0.0 tag for small, very targetted fixes which are already lining up

release-1.1 - This is a small incremental release that we want to push relatively soon so we wanted to manage it separately from develop and to limit scope of changes.

These are the merging rules we are establishing:

If a code change is made in release-1.1, it must be merged up to develop.

If a code change is made in hotfix-1.0.1, it must be merged up to release-1.1.

Nobody except for one team member should merge anything into master and that merge only happens when a product version is about to be shipped.

My questions are:

When should the merges take place? As soon as the fix is applied in lower-level branch? Or periodically in chunks of changes? If periodically, how do you typically determine merge period?

Who should do the merges? Person making the original code change? Or one individual who would be designated as "Director of Git Services"?

Reason I'm asking all this is because it seems that while Git is very flexible (and I do love that part about it), it also allows you to easily shoot yourself in the foot. With just few commands, someone could easily, and hopefully not on purpose, merge new development right into hotfix that should ship out in 2 days.

Many of us are new to Git and we are still feeling our way around the tool. I was thinking how my other companies/teams handled such concepts in the past and I think the biggest difference is that most other source control products that I've used, work with individual commits, so each developer could be responsible for making sure his fixes are applied to the correct places.  But with Git, when one developer runs:

```<code>git checkout release-1.1
git merge hotfix-1.0.1
</code>```

... after his commit, those commands will end up merging an entire branch including code that he has never seen before and may not be the best person to resolve, if there are any conflicts.

答:
You hit the nail on the head -- git is a powerful tool. And like any other powerful tool you can just as easily cut off your hand as you can build a countertop. </p>

<p>The best way to address this stuff is have a continuous integration system backing everything -- it will let you get notified when commits happen and can do things like run your test suite to ensure nobody broke anything. Which is an issue no matter what SCM you are using or even if you are using SCM at all. </p>

Body:
You hit the nail on the head -- git is a powerful tool. And like any other powerful tool you can just as easily cut off your hand as you can build a countertop.

The best way to address this stuff is have a continuous integration system backing everything -- it will let you get notified when commits happen and can do things like run your test suite to ensure nobody broke anything. Which is an issue no matter what SCM you are using or even if you are using SCM at all.


答:
I used fabric to setup deployment in my new startup.

Updating the live server is as simple as:

```<code>fab prod upgrade
</code>```

This gets all of the latest source, puts up a maintenance page, migrates the database, sets up the new code, gets all the dependencies, stops/starts everything, etc.  All of the pertinent information (passwords, usernames, etc.) are all asked upfront.

I just run the command, input some info, and go get a cup of coffee.  Everything's all live by the time I get back.

Title: Describe the best deployment environment you've worked with

Body:
The Joel Test includes the question:

Can you make a build in one step?

Which is important, but I'm wondering, how streamlined have some of the deployment processes been?

All software from shrink-wrap to web applies: what's the best deployment environment you've worked with, and what steps were involved?

Body:
I used fabric to setup deployment in my new startup.

Updating the live server is as simple as:

fab prod upgrade

This gets all of the latest source, puts up a maintenance page, migrates the database, sets up the new code, gets all the dependencies, stops/starts everything, etc.  All of the pertinent information (passwords, usernames, etc.) are all asked upfront.

I just run the command, input some info, and go get a cup of coffee.  Everything's all live by the time I get back.


答:
Yeah, that sounds like a reasonable idea.  Off-by-one DIGIT errors are even worse than the infamous off-by-one errors.  Although, it may create confusion for other people (including your future self) to read the code.

A more explanatory name like NANOSEC_PER_SEC seems good, as it would add clarity where it is used for time.  However, it makes no sense to use in contexts other than time, and it would be impractical to create a separate 1,000,000,000 for every situation.

What you really want to do, silly as it seems at first, is 'divide over sec'.  This leaves NANO_PER, which is not only language-independent (10^9 in America and Europe) but also situation-independent (no limiting on the units), and it is easy to type and read.


问:
Most human-friendly way to order class method definitions?
In any given class definition, I've seen the method definitions ordered in various ways: alphabetical, chronological based on most common usage, alphabetical grouped by visibility, alphabetical with getters and setters grouped together, etc. When I start writing a new class, I tend to just type everything in, then reorder when I'm done writing the entire class. On that note, I've got three questions:

Does order matter?

Is there a "best" order?

I'm guessing there's not, so what are the pros and cons of the different ordering strategies?

答:
Ideally, your classes are so small that it doesn't matter. If you only have a dozen methods, and your editor or IDE supports folding, you don't have a problem, because the entire list of methods fits in 12 lines.

Failing that, the top-level distinction should be public vs. private. List the public methods first: these are what people are going to be looking for the most, because they define the way your class interfaces with the rest of the codebase.

Then, inside each of these, it makes the most sense to group methods by functionality: constructors and destructors in one block, getters/setters in another, operator overloads, static methods, and the rest of the bunch. In C++, I like to keep operator= close to the constructors though, because it's closely related to the copy constructor, and also because I want to be able to quickly spot whether all (or none) of default ctor, copy ctor, operator= and dtor exist.


答:
Implementing a commit and release process is one way to minimize the risks.  As for committing to the wrong branches, that can be difficult to enforce.  But you just need to manage it so that people understand the process and that it isn't too difficult.  Generally, that they only work on one branch and should not be merging at all.

Another option would be to add a code review tool so that features are vetted before going into production.

Gerrit - prevents commits from being pulled until they are
approved

ReviewBoard - another code review tool, just review the diff before merging into the production branch (with no one actually making commits to that branch)

The main thing is creating a simple, documented process that people can follow.  Generally, having people know which branch that they are supposed to be working on and designating who is responsible for merging branches can help keep things simple.

Title: Looking for good practices on managing branches and developers in Git

Body:
I a little while ago I joined a new development team and recently we had our first major release. We've used Git since the beginning of the project and by now are somewhat comfortable with it. However, now that the product is in the field, we are discovering new issues/processes that need to be established. Up to this point, everything we've done was by referencing the very popular successful branching model post, which indeed has been very helpful

Currently we have the following branches, all live and all being updated:

master - only released, stable code (tagged every time release is cut)

develop - wide open. used for long term development

hotfix-1.0.1 - branched off master's 1.0.0 tag for small, very targetted fixes which are already lining up

release-1.1 - This is a small incremental release that we want to push relatively soon so we wanted to manage it separately from develop and to limit scope of changes.

These are the merging rules we are establishing:

If a code change is made in release-1.1, it must be merged up to develop.

If a code change is made in hotfix-1.0.1, it must be merged up to release-1.1.

Nobody except for one team member should merge anything into master and that merge only happens when a product version is about to be shipped.

My questions are:

When should the merges take place? As soon as the fix is applied in lower-level branch? Or periodically in chunks of changes? If periodically, how do you typically determine merge period?

Who should do the merges? Person making the original code change? Or one individual who would be designated as "Director of Git Services"?

Reason I'm asking all this is because it seems that while Git is very flexible (and I do love that part about it), it also allows you to easily shoot yourself in the foot. With just few commands, someone could easily, and hopefully not on purpose, merge new development right into hotfix that should ship out in 2 days.

Many of us are new to Git and we are still feeling our way around the tool. I was thinking how my other companies/teams handled such concepts in the past and I think the biggest difference is that most other source control products that I've used, work with individual commits, so each developer could be responsible for making sure his fixes are applied to the correct places.  But with Git, when one developer runs:

```<code>git checkout release-1.1
git merge hotfix-1.0.1
</code>```

... after his commit, those commands will end up merging an entire branch including code that he has never seen before and may not be the best person to resolve, if there are any conflicts.


问:
When to store values in constants/finals
This might seem like an odd question, but I'm worried that I'm putting too many things as constants/finals at the top of my java class. I've started to put every value that is in my program into a constant (At least the ones that influence it's overall effect). The reason I'm doing it is because then it's easy to find the values and change them latter, even if they are only used once, it's easier to find them at the top. Is this a bad or good practice, I really have no idea.

Here's an example:

```<code>private static final Color COLOR_SELECTED = Color.BLUE;
private static final Color COLOR_ALTERNATE_ONE = Color.WHITE;
private static final Color COLOR_ALTERNATE_TWO = new Color(240, 240 , 240);
private static final Color TEXT_COLOR = Color.black;
</code>```

答:
No, this is not a bad thing. Your code will be able to refer to TEXT_COLOR and consistently get Color.black. Even if you only use it once now, you might use it more than once as your code continues to develop.

An even better thing would be to read these values from a properties file, so you could change them without recompiling. But that's only something to worry about if you think the colours used might actually change in the future.


答:
This is a good practice! This is equivalent to the idea of removing magic numbers.

In the future, if you want to change the color of something that is selected, you can do it in one place. Trying to look for every instance of Color.BLUE might not be incorrect if a different item also uses the color blue.

Title: When to store values in constants/finals

Body:
This might seem like an odd question, but I'm worried that I'm putting too many things as constants/finals at the top of my java class. I've started to put every value that is in my program into a constant (At least the ones that influence it's overall effect). The reason I'm doing it is because then it's easy to find the values and change them latter, even if they are only used once, it's easier to find them at the top. Is this a bad or good practice, I really have no idea.

Here's an example:

```<code>private static final Color COLOR_SELECTED = Color.BLUE;
private static final Color COLOR_ALTERNATE_ONE = Color.WHITE;
private static final Color COLOR_ALTERNATE_TWO = new Color(240, 240 , 240);
private static final Color TEXT_COLOR = Color.black;
</code>```


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答: Pointers make way more sense if you've studied assembly language and/or computer architecture. I think that if I teach a C class, I would start with a couple weeks of architecture to explain the memory model and the kinds of instructions the processor actually executes.

Title: What's a nice explanation for pointers?


答:
For one or two usages, I would use the convention:

```<code>tv_sec = timeInNanosec / (1000 * 1000 * 1000);
tv_nsec = timeInNanosec % (1000 * 1000 * 1000);
</code>```

It's perfectly self explanatory, gets compiled to a constant and it's hard to screw up.

Also, it's very useful in cases such as:

```<code>var Time = 24 * 60 * 60;
</code>```

where it's easy to see we are talking about one day in seconds.

Body:
For one or two usages, I would use the convention:

tv_sec = timeInNanosec / (1000 * 1000 * 1000);
tv_nsec = timeInNanosec % (1000 * 1000 * 1000);

It's perfectly self explanatory, gets compiled to a constant and it's hard to screw up.

Also, it's very useful in cases such as:

var Time = 24 * 60 * 60;

where it's easy to see we are talking about one day in seconds.


问:
Scala string interpolator: ad-hoc feature of general construct?
In Scala 2.10 a new string interpolator feature has been added (see here).

For example

```<code>val name = "James"
println(s"Hello, $name") // Hello, James
</code>```

What is not clear to me is whether this feature is an ad-hoc addition or whether it is syntactic sugar for some other, more general construct.

The only thing I can think of is that the compiler turns a string literal like

```<code>s"Hello, $name"
</code>```

into an expression like

```<code>"Hello, " + name
</code>```

but still, this seems to me a very special treatment of string literals (see also the related question on XML literals).
Or is this a particular application of some more general Scala construct?

EDIT

Thanks for the feedback. I had read the whole article but probably my summary was not accurate enough, making the point of my question unclear. Thanks to Jörg for the good summary.

What puzzles me is that the compiler expands a special string literal into an expression that contains names defined inside the string itself. The resulting expression must be re-compiled to check that the names of the arguments used to call the StringContext instance are defined in the current lexical scope.

This looks like some kind of pre-processing to me (first pass: expand special literals, second pass: compile) because the value of the token s"Hello, $name" is preprocessed and expanded into a whole sub-tree of the syntax tree.

This expansion is built-in into the compiler: as far as I know it cannot be defined in terms of the language itself by means of more primitive features taking the string literal as it is as input because the names defined inside the string must be extracted and interpreted as variables from the lexical scope.

For example, (as far as I understand) no Scala method can be called with the string "Hello, $name" and find out that there is a variable name in the lexical scope of the expression where the method has been called.
Therefore, it is the compiler that has to write out

```<code>StringContext("Hello ").s(name)
</code>```

and then re-compile the result, check that the variable name exists, and generate a proper method call.

Summarizing, I find this reference to a variable in the lexical scope from within a string literal very strange, it seems something is happening on a different level of the language. I do not know how to explain this in a better way.

答:
The translation is explained in the very article you linked to:

```<code>foo"bar"
</code>```

is translated to

```<code>StringContext("bar").foo
</code>```

and

```<code>foo"bar $baz quux $frob blurb"
</code>```

is translated to

```<code>StringContext("bar ", " quux ", " blurb").foo(baz, frob)
</code>```

You can add your own methods to StringContext using the pimp-my-library pattern.

Yes, this is a special treatment for string literals. There is no similar feature for numeric literals. However, your method can be arbitrarily complex and even contain a full-blown parser, so you can build your own numeric notation  for numbers. E.g.:

```<code>implicit class RomanNumerals(val sc: StringContext) extends AnyVal {
  def roman() = if (sc.parts(0) == "V") 5 else 10 // Stub implementation
}

val n = roman"X"
// n: Int = 10
</code>```

As you can see, the return type of your string interpolation method doesn't have to be a String. In other words: the result of interpolating a string doesn't have to be a string.

Body:
The translation is explained in the very article you linked to:

foo"bar"

is translated to

StringContext("bar").foo

and

foo"bar $baz quux $frob blurb"

is translated to

StringContext("bar ", " quux ", " blurb").foo(baz, frob)

You can add your own methods to StringContext using the pimp-my-library pattern.

Yes, this is a special treatment for string literals. There is no similar feature for numeric literals. However, your method can be arbitrarily complex and even contain a full-blown parser, so you can build your own numeric notation  for numbers. E.g.:

implicit class RomanNumerals(val sc: StringContext) extends AnyVal {
  def roman() = if (sc.parts(0) == "V") 5 else 10 // Stub implementation
}

val n = roman"X"
// n: Int = 10

As you can see, the return type of your string interpolation method doesn't have to be a String. In other words: the result of interpolating a string doesn't have to be a string.


问:
Ship Early, Ship Never
This started as a "Note to Self," so please excuse me if the frustration is all too evident and the writing is less than stellar...

Three major subjects I've had at the forefront of my mind lately:

Motivation

Learning (Curiosity)

Doing (Making)

I've been studying motivation and incentives for months now. It seems there are an infinite number of different motivations that people might have for doing things (I realize that sounds trite but bear with me). I've been really drawn to it because I'm desperate to find out why I do the things I do and why I don't do the things that I want to do but don't do.

I'm in the midst of reading Paul Graham's excellent Hackers and Painters book. In it, he makes the case that hackers and painters are very similar because they are both "makers." Painters make paintings. Hackers make software. Painters don't necessarily need to understand the chemical composition of paint to make beautiful paintings. And hackers don't necessarily need to know 1's and 0's to make beautiful software.

Graham then draws the distinction between disparate computer science fields:

some people seem to be studying mathematics

some people seem to be studying the computers themselves

the hackers are making software.

The difference is incredibly important. It seems the motivation for some is to make beautiful things. And the motivation for the others is to learn out of curiosity. Certain motivations seem obvious to me, but curiosity seems a bit less obvious. I would certainly consider myself as a curious person with a seemingly unquenchable thirst to learn just about everything I can. But this is exactly where the problem comes up.

The thing that scares me so much is that I desperately want to make things. I desperately want to do things. I want to write a book. I want to paint a painting. I want to compose a song. I want to do things like travel. But the strangeness is that I also want to learn things. I want to learn to play guitar. I want to learn about art history. I want to learn more about philosophy and literature.

The key seems to be the balance between learning and doing... between studying and making.

While I'm not sure how much one should learn about a given thing before doing it, I know for certain that I find myself constantly on one side rather than the other. As it stands now (and as far as I can tell I've always been this way), I am a learner and not a doer. I've read great books. I've practiced guitar for years. I've spent countless hours studying programming.

But I've written 0 books. I've composed 0 songs. I've coded 0 beautiful programs. I've painted 0 beautiful paintings. I've started 0 viable businesses.

The scary part of all this is that there are probably countless unfinished works of art in the world. Is this my misanthropic revenge against society and culture to never produce or finish any of the works of art that I start? Perhaps the worst part (aside from this being my natural inclination), is the fact that I f***ing know better. I just finished books like "Getting Things Done" and "Making Ideas Happen." I've aggregated and synthesized countless words of wisdom on how to do things and how to make things.

Imagine the horror of going through life without being able to do the things you want to do. If this is something you've struggled with (and hopefully overcome), please share. If not... perhaps some delicious pity would make me feel better.

[UPDATE: Just wanted to send a quick thanks to everyone that shared their thoughts. I deliberately left the question somewhat open-ended in hopes of encouraging discussion and having others refashion the central problem around their similar experience, and I think it worked out great... there's a lot of amazing insight here to work with and it was really helpful. Thanks again.]

答:
I know the problem so well, and in my case it's partly due to a short attention span. One of the things that seperates the doers from me, is a number of things :

Perfection

I want everything I do to be perfect. So I can sit literally countless hours overhearing the same 8 bars in a song I composed. I keep on trying until it is perfect, but I forget one thing: Sometimes getting it perfect requires to throw everything away and start anew. A too great desire for perfection just leaves a work unfinished as you can't get it perfect. So in fact, it will never be finished as there's always something else that has to be changed. Which brings me to

Frustration

That's what it is: You work on something, and it doesn't want to work out like you do. At a certain point I become so tired of it that the inspiration is gone. Not only do I have no clue how to get things more perfect, I don't have the will anymore to keep on looking for it as well. Basically, I enter the stage of

Boredom

Indeed, work too long on any project and it starts boring you. There's something new on the horizon you want to try. A new challenge that has to be faced, a new problem that has to be solved. And that starts drifting your attention away from the things you were trying to finish. These things get abondoned, and another unfinished piece of art will quickly depart in oblivion.

This sounds a bit contradictory to the perfection I want, but essentially they're three sons of the same father: no real sense of direction and goal. Starting is difficult because the ultimate goal is so broadly formulated you can't just do it in a day. So you have to divide the work in smaller tasks. Keeping on it is difficult as there is a lot of repetitive stuff where you quickly get bored.. Editing is such a thing, code review, testing, writing manuals,... Difficult to keep the end result in mind when you get tired of something. And in the end of the day finishing it is impossible because even when you get through the first two stages, your call for perfection doesn't allow you to decide when the goal is met.

Funny thing is, once I realized that, I managed to get more things done by:

being picky on what I start. One can't do everything in life, and some things are just not meant for me. Painting is one for example

force myself to finish things at least a week before I want it to be finished. Leaves me some time for extra perfection, although I have to guard myself that I don't start rethinking the design in the last week.

give up on things that go nowhere, and do so quickly enough to not get frustrated about it.

learn -yeah, learn- a bit by practicing very small bits, so I can get the hang of how to avoid too much boring work and how to get it done more efficiently.

It's not a foolproof way, as I have a short attention span anyway. But it helps, and it's more "me" than all that "getting things done" stuff. I had 6 notebooks and agendas this year, I lost all of them. So I fumble on in the good ol' chaotic way. Yet, realizing how it works for me actually makes me more productive. Or at least, avoids I dive into the same pitfall once too often...

Title: Ship Early, Ship Never


问:
Why is it a good idea for "lower" application layers not to be aware of "higher" ones?
In a typical (well-designed) MVC web app, the database is not aware of the model code, the model code is not aware of the controller code, and the controller code is not aware of the view code. (I imagine you could even start as far down as the hardware, or perhaps even further, and the pattern might be the same.)

Going the other direction, you can go just one layer down. The view can be aware of the controller but not the model; the controller can be aware of the model but not the database; the model can be aware of the database but not the OS. (Anything deeper is probably irrelevant.)

I can intuitively grasp why this is a good idea but I can't articulate it. Why is this unidirectional style of layering a good idea?

答:
Layers should not have two-way dependencies

The advantages of a layered architecture are that the layers should be usable independently:

you should be able to build a different presentation layer in addition to the first one without changing the lower layer (e.g. build an API layer in addition to an existing web interface)

you should be able to refactor or eventually replace the lower layer without changing the top layer

These conditions are basically symmetrical. They explain why it's generally better to have only one dependency direction, but not which.

The dependency direction should follow the command direction

The reason why we prefer a top down dependency structure is because the top objects create and use the bottom objects. A dependency is basically a relationship that means "A depends on B if A can't work without B". So if the objects in A use the objects in B, that's how dependencies should go.

This is in a way somewhat arbitrary. In other patterns, such as MVVM, control easily flows from the bottom layers. For example you can set up a label whose visible caption is bound to a variable and changes with it. It's normally still preferable to have top down dependencies, though, because the main objects are always the ones the user interacts with, and those objects do the majority of the work.

While from the top down we use method invocation, from the bottom up (typically) we use events. Events allow dependencies to go top down even when the control flows the other way around.
The top layer objects subscribe to events on the bottom layer. The bottom layer does not know anything about the top layer, which acts as a plug in.

There are also other ways of maintaining a single direction for example:

continuations (passing a lambda or a method to be called on and event to an async method)

subclassing (create a subclass in A of a parent class in B which is then injected in the bottom layer, a bit like a plugin)


问:
What should the relation between parent and child GUI components be?
This seems to happen every time I create any sort of GUI. I have trouble figuring out how child classes should communicate to their siblings.

It's a general problem, but it's probably easier to use a concrete example (hopefully that's still okay for this forum? I know it's different from StackOverflow): I have a window that contains 4 panels. Right now, I simply have the children as member objects of the parent.

Keypresses change all 4 panels, so I have the child objects throw the event back to their parent, which does the logic, then makes the appropriate calls for each panel.

However, mouse events are different. They change the position of a camera (owned by the parent), which every panel uses to render itself. So I must recompute a few matrices, in order to render each panel. The matrices are different for each panel. The problem I'm having is: when do I give the children the matrices?

I think I have three possibilities:

When reading a mouse event, compute the matrices and call setter methods for each panel. However, sometimes the matrix will be replaced before the window renders.

Give the child panel a reference to the parent, and during the render call, request the matrix from the parent (either by method or member variable).

Modify child.render() so that it accepts two matrix parameters, and make parent.render() call them appropriately.

#2 seems good, because I'm not unnecessarily setting the matrix in the child window. But it also requires me to mess with forward declarations for member objects, which seems like bad practice. And #3 I'm not quite sure how to implement, because render is called by many things other than my code (un-minimizing, for example), and I can't touch them. So I suppose it is #1?

Is there a design pattern people usually follow for this? Am I just overthinking, and #1 is actually completely OK?

答:
If I got your right, during the render call, the child needs a service which provides some matrixes, right? It does not really matter that it is the parent which provides that matrixes. So create an interface like IMatrixProvider, give a reference to an object of type IMatrixProvider during construction time to your panels and call that service when you need it within the rendermethod. Your parent object can implement that interface, if the matrixes are provided from there.

If you use a functional language or a language with functional elements, you may not even need a full "interface object", a simpler "call back" or "delegate function" may be enough.

This is mostly what you described under #2, but not with a reference to the full parent object - so the panels stay decoupled from the parent type.


问:
Software Architecture Modelling
I am a little confused at how best to visually model a space-based architecture (SBA)  for presenting the system/software architecture design to a client.

The goal of this modelling is to show:

The major components of the system (e.g.: databases, server exposed API, client, server workers, client exposed API)

Interactions between these major components

Primary end-to-end workflows

Currently I am thinking to use BPMN2 notation with swimlanes; and sequence & use-case diagrams in UML2 notation.

Not sure if this approach is best, would be great to get some feedback :)

答:
Agree with the previous answer. As mentioned there, the model types mentioned in the question will not help you alone.

In case of a non-trivial data model or business domain, I recommend to start with an entity relationship diagram. It is easy to understand, the few symbols are quickly explained.
Include proper definitions of the entities. This will make sure everyone has the same understanding of the domain. The relations with the cardinalities will also sort out many misunderstandings in advance.

A block diagram is usually the main diagram to show the runtime composition of the architecture. Indicate protocol and system boundaries. Choose an abstraction level which fits the purpose, and then be as specific as you can with the elements you show. E.g. in a communication channel, indicate who initiates the request, the data flow direction, and the protocol used. Describe the purpose of each component and connection in additional text below the model in case it is not trivial or obvious.

SAP uses a slimmed down UML version for architecture (as described here).

You might use the other diagram types if required.

Don't forget that there might be a design time view of an architecture which is different from the runtime view. E.g. you might have layers in the design time which are collapsed by a compiler for the runtime.

Title: Software Architecture Modelling


答: When you think about why you wrote "1 Billion" instead of "1000000000" in your question title, you'll realise why the answer is yes.</p>


问:
Should I make a seperate unit test for a method, if it only modifies the parent state?
Should classes, that modify the state of the parent class, but not itself, be unit tested separately? And by separately, I mean putting the test in the corresponding unit test class, that tests that specific class.

I'm developing a library based on chained methods, that return a new instance of a new type in most cases, where a chained method is called. The returned instances only modify the root parent state, but not itself.

Overly simplified example, to get the point across:

```<code>    public class BoxedRabbits
    {
        private readonly Box _box;
        public BoxedRabbits(Box box)
        {
            _box = box;
        }

        public void SetCount(int count)
        {
            _box.Items += count;
        }
    }

    public class Box
    {
        public int Items { get; set; }
        public BoxedRabbits AddRabbits()
        {
            return new BoxedRabbits(this);
        }
    }

var box = new Box();
box.AddRabbits().SetCount(14);
</code>```

Say, if I write a unit test under the Box class unit tests:

```<code>box.AddRabbits().SetCount(14)
</code>```

I could effectively say, that I've already tested the BoxedRabbits class as well. Is this the wrong way of approaching this, even though it's far simpler to first write a test for the above call, then to first write a unit test for the BoxedRabbits separately?

答:
If the class really is as trivial as that and the rest of your test suite is sufficiently complete, then there's a fairly high degree of certainty that the test coverage of the trivial class is pretty high and any change to that class's API or functionality will inevitably affect several unit tests. If that's the case, I'd do without the additional unit test.

If, however, the class went beyond non-trivial and involved any kind of language syntax that can be changed from anywhere else in the source (a header that defined configuration variables/typedefs), or data structures that are implementation-dependent, then I would certainly create a unit test.


问:
Suggestions on how can I implement a generic matching system for users?
I need help with coding something. I'm trying to design a system that will allow users to setup rules for the system to process (similar to email processing rules, in a way). When I receive a chunk of data (in this case, it is a object that has properties with values related to the client system's hostname, OS version, etc.) I want the user to be able to create a criteria like "when the hostname equals 'somehost' or the OS version is greater than 6, etc.

The table I have so far has a record ID, a column for holding the name of the value I'm checking (like the property name, e.g. object.Hostname stores as "Hostname"), a two character code for the operator (EQ, NE, GT, etc), the value to compare against and a foreign key value.

I don't have a warm fuzzy about it, though. Am I going down the right path? I wanted the matching to be flexible. I'm visualizing putting the class properties in a dropdown so that the user can select the property, type in a search value and select the criteria. Thoughts?

Thanks!

答:
Your design is correct. I assume that:

your ID is not set to auto increment, because it would mean, that it is not possible to add more than one condition to a certain rule

regarding the above point - you want to have more than one condition per rule.

I would suggest adding another column for the logical connection between each condition (OR;AND), unless ofcourse conditions in a rule are always OR or AND connected. I am assuming this because you wrote

when the hostname equals 'somehost' or the OS version is greater than 6, etc.

The architecture is not an overkill - it is minimalist and it will pay off! I would have normalized the tables even more:

Rules

Conditions

Operators

Properties

Values

and so on

Where i work, we have a custom rule engine exactly for such purposes and it is designed more or less the way you described it.


问:
Algorithm, AI, or intelligent agent suggestions for ingesting poorly-formatted & variable data from different document types
Thanks for looking!

Background

I have been tasked with writing a program to normalize and ingest data from various sources to a common database.

For the sake of simplicity, let's say that the program is for a public library system, and that they are wanting to maintain a database of all books currently lent out of their various branches.  Let's further assume that the branches are not linked to a common network or database (silly, I know, but please bear with me).

The task is to accept submitted data from the various branch managers, and then automate the process of normalizing that data and storing it into the common database.

Variable raw data formats

The raw data may be submitted in the form of a MS Excel file, a .csv, a tab-delimited file, a plain text file, possibly even just a simple email, a field delimited file, etc.

Loosely related data contents

The contents of the raw data files will generally contain these fields:

Book ID

Book Title

Author

Is Checked Out?

Days Overdue

ISBN

Due date

. . .and so on.  The problem is that some of the submitted data files will have these fields in column headers and some will not (so will need to infer from data what the field is).

Further, the field names will not always be consistent.  One library branch may call the boolean field for whether a book is checked out "OnLoan", while another branch calls it "IsCheckedOut".

Common data repository

All of this data will be ingested to a common database with normalized data that has been cleaned up during the ingest process.

So, hopefully, we have something like this in the final DB:

BranchId

BookId

Title

CheckedOut

ISBN

DueDate

DaysOverdue

. . .and so on.

Automation of Ingest Process

Let's assume that there are thousands of branches and that they must each issue this report to the Library HQ once monthly.

Obviously, my client can hire a bunch of data-entry people to do this job (in fact, that is how it is done today).  The request from them however, is to automate as much of this as possible to cut data-entry costs.

So here is my plan, please suggest or criticize away:

Standardize the file submission process.  This will be handled by creating a web page with a file upload dialog, DONE!

Determine the file type.  I will be using C# (not that language matters) and it has a pretty easy way of getting the file type but sometimes I will simply get a .txt that turns out to be tab or pipe-delimited so I need an algorithm to detect this.  I am thinking of using a Bayes Classifier or Artificial Neural Network for this.

Attempt to parse the data into memory.  Now I have hopefully determined if I have an excel file, a tab-delimited, a csv, etc.  I will run the file through the correct parser to get it into memory but now need to determine if the file has headers or if I can infer what the headers should be by the value.  For this I hope to again use a Bayes Classification system and perhaps calculate a Levenshtein Distance from the value to items in an array of known/standardized header names.  But what about header inference from the data?  How would I identify one column as containing due dates and one as containing ISBN numbers?

Glean, clean and submit the values in each column.  If I am lucky enough to have gotten this far (I know what the headers are), then I need to loop through the values in each column and clean/normalize them.  For example, some library branches may enter an ISBN value as "ISBN12-345-67-89" whereas another branch enters "123456789".  I need to catch that difference and normalize them.  Is this a case for just a plain ol' expert system or if. . .then?  Is there a better way?

Submit normalized data to database.  This step is not as trivial as it sounds because some library branches may report a book title as "Algorithms for Dummies" while another reports it as "Algorithms for Dummies, 1st Edition".  Let's assume for a second that I don't have an ISBN to tie the two books together (though they are the same), what method might be suitable for deducing that these books are the same and assigning them a common primary key int the related Books table?

Many, Many thanks for your suggestions!!!

答:
Regular batch or bulk processing of divergent data sources is proven practice that follows a common strategy.

For the example given, there seems to be a strong intent to do a lot of ongoing dynamic data analysis that probably isn't necessary as an ongoing activity for this kind of process, and will add a great deal of unnecessary complexity to the example system.

Yet, some of the techniques mentioned might be useful for initial format discovery, analysis, and definition where a layout cannot be provided by each source in either a timely or accurate manner.  Each submission will have characteristics that will make it unique from both other submissions and other submitters.  Those characteristics are markers.  During the transfer, or upload of the submission we can capture some of that information.  The rest of the information used as markers will come from particular inspection points of the content of the submission.

Once a format is determined (and periodically validated), we would only need to locate necessary markers in subsequent submissions to determine which format the submission follows.  After we know which format a submission follows, we can choose an appropriate adaptor to apply during the batch of the job.

As far as points four and five, that is slightly less than trivial, but not terribly complex.  Just like with dates, the individual pieces of data may take several different forms, or formats.  Each source will likely be consistent about which format they choose in their submission.

It then becomes a matter of matching to known formats and determining which detail we must include, what detail we can discard, and what detail we may infer (based on other disconnected but related information).  If we cannot infer the missing data for a  format, then the data is simply in an incomplete state that may suggest manual entry or rejection.  There may even be well known formats that automatically flag a record or series of records as manual entry or rejected.

Occasionally, submissions won't follow the format created.  Perhaps the entire submission, or perhaps just a few records do not follow the format.  In either case, determining why is more important than determining how and what is next.  Why can't be determined by any software except in trivial, predicted cases.  Why is a business value that we won't have the answer to in a simple technical solution. So it is a question that will be asked out of cycle.  It may very well lead us back to a how and a what, but first things should clear as to why it changed and why it is broken.


答:
Reasons Not To

Firstly, here is a reason not write any underscores or use any trick to simulate it: it makes the constants harder to find in the code. Suppose that some program exhibits, somewhere in its operation, hard-coded value 1500000 for some parameter.  I want to know where in the source code of the program this actually occurs, so I grep the code for 1500000, and find nothing. Why? Might it be in hexadecimal (but why for such a round decimal number). Unbeknownst to me, the constant is actually written as 1_500_000. I needed the regex 1_?500_?000.

Guiding Characters in Comment

Just because one kind of visual aid is not available, or we don't wish to use it for the above reason, doesn't mean that we cannot take advantage of the two dimensions of the text file to create an alternative visual aid:

```<code>foo = bar / 1000000000;
//           --^--^--^
</code>```

With this we can easily convince ourselves that there are three groups of three zeros. Yet, we can still grep the source code for 1000000000 and find it.

Syntax Coloring

A text editor with programmable syntax coloring can be made to color groups digits in numeric constants with alternating colors for better readability. We don't have to do anything in the code.

Preprocessing: C, C++, Objective C

Now, if we really want some commas between digits, in C and C++ we can use some preprocessing:

```<code>/* Four digit base TH-ousand constant macro */
/* Condensed using Horner's rule */
#define TH(A,B,C,D) ((((((A) * 1000) + (B)) * 1000) + (C)) * 1000 + D)

tv_sec = nanoseconds / TH(1,000,000,000)
</code>```

Works for numbers like TH(1,234,567,890).

A macro similar to TH can also work with token pasting rather than arithmetic. In the C preprocessor, the binary ## operator ("token paste") can be used in a macro body in order to paste together two operands into a single token. One or both of the operands can be macro arguments.  The downside here (creating a risk for us) is that if the resulting catenation isn't a valid token, the behavior is undefined.

```<code>#define TOK4(A, B, C, D) A ## B ## C ## D
</code>```

Now

```<code>TOK4(1,000,000,000)       /* produces the single token 1000000000 */
TOK4(1,123,000,000.0E+2)  /* produces the single token 1123000000.0E+2 */
TOK4(pr,in,t,f)           /* produces the token printf */
TOK4(#,*,a,b)             /* undefined behavior, #*ab is not valid token syntax */
</code>```

C programs that paste together identifiers and use the results to name global variables and functions exist and are awful to work with because they are impervious to tools like GNU id-utils and ctags.

Body:
Reasons Not To

Firstly, here is a reason not write any underscores or use any trick to simulate it: it makes the constants harder to find in the code. Suppose that some program exhibits, somewhere in its operation, hard-coded value 1500000 for some parameter.  I want to know where in the source code of the program this actually occurs, so I grep the code for 1500000, and find nothing. Why? Might it be in hexadecimal (but why for such a round decimal number). Unbeknownst to me, the constant is actually written as 1_500_000. I needed the regex 1_?500_?000.

Guiding Characters in Comment

Just because one kind of visual aid is not available, or we don't wish to use it for the above reason, doesn't mean that we cannot take advantage of the two dimensions of the text file to create an alternative visual aid:

foo = bar / 1000000000;
//           --^--^--^

With this we can easily convince ourselves that there are three groups of three zeros. Yet, we can still grep the source code for 1000000000 and find it.

Syntax Coloring

A text editor with programmable syntax coloring can be made to color groups digits in numeric constants with alternating colors for better readability. We don't have to do anything in the code.

Preprocessing: C, C++, Objective C

Now, if we really want some commas between digits, in C and C++ we can use some preprocessing:

/* Four digit base TH-ousand constant macro */
/* Condensed using Horner's rule */
#define TH(A,B,C,D) ((((((A) * 1000) + (B)) * 1000) + (C)) * 1000 + D)

tv_sec = nanoseconds / TH(1,000,000,000)

Works for numbers like TH(1,234,567,890).

A macro similar to TH can also work with token pasting rather than arithmetic. In the C preprocessor, the binary ## operator ("token paste") can be used in a macro body in order to paste together two operands into a single token. One or both of the operands can be macro arguments.  The downside here (creating a risk for us) is that if the resulting catenation isn't a valid token, the behavior is undefined.

#define TOK4(A, B, C, D) A ## B ## C ## D

Now

TOK4(1,000,000,000)       /* produces the single token 1000000000 */
TOK4(1,123,000,000.0E+2)  /* produces the single token 1123000000.0E+2 */
TOK4(pr,in,t,f)           /* produces the token printf */
TOK4(#,*,a,b)             /* undefined behavior, #*ab is not valid token syntax */

C programs that paste together identifiers and use the results to name global variables and functions exist and are awful to work with because they are impervious to tools like GNU id-utils and ctags.


答:
I would do this:

```<code>const int Million = 1000 * 1000;
const int Billion = 1000 * Million;
</code>```

or

const int SciMega = 1000 * 1000;
const int SciGiga = 1000 * SciMega;

Regarding number of nanoseconds per second: nano is the "inverse" of giga.

```<code>Kilo  Mega  Giga   etc.
10^3  10^6  10^9
Milli Micro Nano   etc.
10^-3 10^-6 10^-9
</code>```

Note the "Sci" - for scientific, as in computers, the meanings of kilo, mega, giga etc. are different: 1024 (2^10), 1024*1024 (2^20), etc.
2 megabytes is not 2,000,000 bytes.

UPDATE Commenter pointed out that special terms exist for digital exponents of 2: http://en.wikipedia.org/wiki/Mebibyte

Body:
I would do this:

const int Million = 1000 * 1000;
const int Billion = 1000 * Million;

or

const int SciMega = 1000 * 1000;
const int SciGiga = 1000 * SciMega;

Regarding number of nanoseconds per second: nano is the "inverse" of giga.

Kilo  Mega  Giga   etc.
10^3  10^6  10^9
Milli Micro Nano   etc.
10^-3 10^-6 10^-9

Note the "Sci" - for scientific, as in computers, the meanings of kilo, mega, giga etc. are different: 1024 (2^10), 1024*1024 (2^20), etc.
2 megabytes is not 2,000,000 bytes.

UPDATE Commenter pointed out that special terms exist for digital exponents of 2: http://en.wikipedia.org/wiki/Mebibyte


问:
What does "deploy to a physical machine" mean
I was asked whether I've ever "deployed to a physical machine" and I'm seeing this terminology when googling, but not getting a definition. What does it mean? What other way could someone deploy an application if not to a physical machine?</p>

答:
The term physical machine referrers to an independent server or real physical computer, and the other term is virtual machine which is a simulated computer running in another computer (often beside other simulations).

The difference for deployment can vary.

A virtual machine can be snapshot and rolled back.

A physical machine can be hard reset.

The setup of a virtual machine is configurable.

Changing a physical machine's setup requires hardware changes.

There are many more, but you get the idea.


问:
Git Branch Model for iOS projects with one developer
I'm using git for an iOS project, and so far have the following branch model:

```<code> feature_brach(usually multiple) -> development -> testing -> master
</code>```

Feature-branches are short-lived, just used to add a feature or bug, then merged back in to development and deleted. Development is fairly stable, but not ready for production.

Testing is when we have a stable version with enough features for a new update, and we ship to beta testers. Once testing is finished, it can be moved back into development or advanced into master.

The problem, however, lies in the fact that we can't instantly deploy. On iOS, it can be several weeks between the time a build is released and when it actually hits users. I always want to have a version of the code that is currently on the market in my repo, but I also have to have a place to keep the current stable code to be sent for release.

 So:

where should I keep stable code

where should I keep the code currently on the market

and where should I keep the code that is in review with Apple, and will be (hopefully) put on the market soon?

Also, this is a one developer team, so collaboration is not totally necessary, but preferred because there may be more members in the future.

答:
I think that you should consider tagging master, when it is sent for release. If you try to match a branch to what is released, you probably will need to monitor the release date then quickly merge to the new branch. Since it is very manual, a tag should suffice.

One thing I like to do is upon release, perform a clone to a new repository. This is the "release" repository and can be setup with limited permissions. Your local repository would then have two remote repositories, so when it is time to release, you merge from one branch to another, then push the result to the release repository. Only you can do this last step and then others on the team can only have permissions to part of the workflow.


问:
Does TDD really work for complex projects?
I’m asking this question regarding problems I have experienced during TDD projects.
I have noticed the following challenges when creating unit tests.

Generating and maintaining mock data

It’s hard and unrealistic to maintain large mock data. It’s is even harder when database structure undergoes changes.

Testing GUI

Even with MVVM and ability to test GUI, it takes a lot of code to reproduce the GUI scenario.

Testing the business

I have experience that TDD works well if you limit it to simple business logic. However complex business logic is hard to test since the number of combinations of tests (test space) is very large.

Contradiction in requirements

In reality it’s hard to capture all requirements under analysis and design.  Many times one note requirements lead to contradiction because the project is complex. The contradiction is found late under implementation phase. TDD requires that requirements are 100% correct. In such cases one could expect that conflicting requirements would be captured during creating of tests. But the problem is that this isn’t the case in complex scenarios.

I have read this question: Why does TDD work?

Does TDD really work for complex enterprise projects, or is it practically limit to project type?

答:
The sad answer is that nothing really works for large complex projects!

TDD is as good as anything else and better than most, but TDD alone will not guarantee success in a large project. It will however increase your chances of success. Especially when used in combination with other project management disciplines (requirements verification, use cases, requirement tractability matrix, code walkthroughs et.c etc.).


问:
What's with Delphi's support cycle?

This is a chart I whipped together showing the length of active (meaning ongoing bug fixes and service packs) support offered for each version of Delphi. It is based on the published support data obtained from Embarcadero's website. Delphi 2010 and XE are excluded because their active support is still ongoing so they can't really be compared accurately.

Ironically, Delphi 7, which was regarded by many to be the most stable until the release of Delphi 2009, had a support cycle three times as long as Delphi 2009. Granted, this chart spans three different companies with three different agendas. My question is why is Delphi 2009's support cycle so short? I understand Embarcadero has a business to run and they don't make money with service packs but really, 12 months? I would expect that of a $10 shareware title with low profit margins not a $900-$3500 world class development tool.

答: Only Embarcadero management can answer this question with any accuracy or authority, and I am guessing they are not going to in a forum such as this.</p>

Title: What's with Delphi's support cycle?


问:
Why are there so many numeric types (bit, int, float, double, long)?
I've learned PHP, Java, and C. Now I'm curious as to why there are so many types of numerical data types like bit, int, float, double, and long. Why not make only one type for numericals?

Is there any benefit to this? Maybe if we use integers to hold such small numbers we can save memory?

答:
Back before we had gigabyte systems (or on modern embedded systems like Arduino), memory was at a premium and so shorthand methods were implemented to specify how much memory a particular number would take up - BIT is straightforward - it would originally occupy only 1 bit of memory.

The other data sizes and names vary between systems. On a 32-bit system, INT (or MEDIUMINT) would generally be 2 bytes, LONGINT would be 4 bytes, and SMALLINT would be a single byte. 64-bit systems can have LONGINT set at 8-bytes.

Even now - especially in databases applications, or programs that have multiple instances running on servers (like server side scripts on websites) - you should be careful about what you choose. Picking a 2, 4, or 8-byte wide integer to store values between 0 and 100 (which can fit in one byte) is incredibly wasteful if you have a database table with millions of records.

More information:
https://en.wikipedia.org/wiki/Integer_(computer_science)


答:
Is there any benefit they make it?

Of course. There are benefits. In the world of computers memory is one of the most important thing to consider. What is the use of having a memory of 2kb when the data can fit in less than 1kb?. Optimizations should be there. If you use more memory it obviously kills your computers speed at a point. Do you really like to have it? No right...?

```<code>int - 2 bytes (16 bits)

long - 4 bytes (32 bits)

long long - 8 bytes (64 bits)

float - 4 bytes
</code>```

Not only the memory but there are organization of type of numbers as well. for an instance floating point. The precision matters a lot and obviously we should have one type which can give us more precision.

If we consider olden days, we had a very less memory as you might know. To save it and use it wisely we had these differences. And much more if you just go ahead and give some try on searching with google.. Hope this helps.

Title: Why are there so many numeric types (bit, int, float, double, long)?

Body:
I've learned PHP, Java, and C. Now I'm curious as to why there are so many types of numerical data types like bit, int, float, double, and long. Why not make only one type for numericals?

Is there any benefit to this? Maybe if we use integers to hold such small numbers we can save memory?

Body:
Is there any benefit they make it?

Of course. There are benefits. In the world of computers memory is one of the most important thing to consider. What is the use of having a memory of 2kb when the data can fit in less than 1kb?. Optimizations should be there. If you use more memory it obviously kills your computers speed at a point. Do you really like to have it? No right...?

int - 2 bytes (16 bits)

long - 4 bytes (32 bits)

long long - 8 bytes (64 bits)

float - 4 bytes

Not only the memory but there are organization of type of numbers as well. for an instance floating point. The precision matters a lot and obviously we should have one type which can give us more precision.

If we consider olden days, we had a very less memory as you might know. To save it and use it wisely we had these differences. And much more if you just go ahead and give some try on searching with google.. Hope this helps.


答:
There are two reasons why you should be concerned with the different numerical data types.

1. Saving memory

```<code>for(long k=0;k<=10;k++)
{
    //stuff
}
</code>```

Why use a long when it could just as easily be an integer, or even a byte? You would indeed save several bytes of memory by doing so.

2. Floating point numbers and integer numbers are stored differently in the computer

Suppose we have the number 22 stored in an integer. The computer stores this number in memory in binary as:

```<code>0000 0000 0000 0000 0000 0000 0001 0110
</code>```

If you're not familiar with the binary number system this can be represented in scientific notation as:
2^0*0+2^1*1+2^2*1+2^3*0+2^4*1+2^5*0+...+2^30*0. The last bit may or may not be used to indicate if the number is negative (depending if the data type is signed or unsigned).

Essentially, it's just a summation of 2^(bit place)*value.

This changes when you are referring to values involving a decimal point. Suppose you have the number 3.75 in decimal. This is referred to as 11.11 in binary. We can represent this as a scientific notation as 2^1*1+2^0*1+2^-1*1+2^-2*1 or, normalized, as 1.111*2^2

The computer can't store that however: it has no explicit method of expressing that binary point (the binary number system version of the decimal point). The computer can only stores 1's and 0's. This is where the floating point data type comes in.

Assuming the sizeof(float) is 4 bytes, then you have a total of 32 bits. The first bit is assigned the "sign bit". There are no unsigned floats or doubles. The next 8 bits are used for the "exponent" and the final 23 bits are used as the "significand" (or sometimes referred to as the mantissa). Using our 3.75 example, our exponent would be 2^1 and our significand would be 1.111.

If the first bit is 1, the number is negative. If not, positive. The exponent is modified by something called "the bias", so we can't simply store "0000 0010" as the exponent. The bias for a single precision floating point number is 127, and the bias for a double precision (this is where the double datatype gets its name) is 1023. The final 23 bits are reserved for the significand. The significand is simply the values to the RIGHT of our binary point.

Our exponent would be the bias (127) + exponent (1) or represented in binary

```<code>1000 0000
</code>```

Our significand would be:

```<code>111 0000 0000 0000 0000 0000
</code>```

Therefore, 3.75 is represented as:

```<code>0100 0000 0111 0000 0000 0000 0000 0000
</code>```

Now, let's look at the number 8 represented as a floating point number and as an integer number:

```<code>0100 0001 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 1000
</code>```

How in the world is the computer going to add 8.0 and 8? Or even multiply them!? The computer (more specifically, x86 computers) have different portions of the CPU that add floating point numbers and integer numbers.

Body:
There are two reasons why you should be concerned with the different numerical data types.

1. Saving memory

for(long k=0;k<=10;k++)
{
    //stuff
}

Why use a long when it could just as easily be an integer, or even a byte? You would indeed save several bytes of memory by doing so.

2. Floating point numbers and integer numbers are stored differently in the computer

Suppose we have the number 22 stored in an integer. The computer stores this number in memory in binary as:

0000 0000 0000 0000 0000 0000 0001 0110

If you're not familiar with the binary number system this can be represented in scientific notation as:
2^0*0+2^1*1+2^2*1+2^3*0+2^4*1+2^5*0+...+2^30*0. The last bit may or may not be used to indicate if the number is negative (depending if the data type is signed or unsigned).

Essentially, it's just a summation of 2^(bit place)*value.

This changes when you are referring to values involving a decimal point. Suppose you have the number 3.75 in decimal. This is referred to as 11.11 in binary. We can represent this as a scientific notation as 2^1*1+2^0*1+2^-1*1+2^-2*1 or, normalized, as 1.111*2^2

The computer can't store that however: it has no explicit method of expressing that binary point (the binary number system version of the decimal point). The computer can only stores 1's and 0's. This is where the floating point data type comes in.

Assuming the sizeof(float) is 4 bytes, then you have a total of 32 bits. The first bit is assigned the "sign bit". There are no unsigned floats or doubles. The next 8 bits are used for the "exponent" and the final 23 bits are used as the "significand" (or sometimes referred to as the mantissa). Using our 3.75 example, our exponent would be 2^1 and our significand would be 1.111.

If the first bit is 1, the number is negative. If not, positive. The exponent is modified by something called "the bias", so we can't simply store "0000 0010" as the exponent. The bias for a single precision floating point number is 127, and the bias for a double precision (this is where the double datatype gets its name) is 1023. The final 23 bits are reserved for the significand. The significand is simply the values to the RIGHT of our binary point.

Our exponent would be the bias (127) + exponent (1) or represented in binary

1000 0000

Our significand would be:

111 0000 0000 0000 0000 0000

Therefore, 3.75 is represented as:

0100 0000 0111 0000 0000 0000 0000 0000

Now, let's look at the number 8 represented as a floating point number and as an integer number:

0100 0001 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 1000

How in the world is the computer going to add 8.0 and 8? Or even multiply them!? The computer (more specifically, x86 computers) have different portions of the CPU that add floating point numbers and integer numbers.