答:
You could black-box sensitive parts of you project and separate them from the rest. Give an easy, well documented interface to interact with those modules without exposing what goes on inside.
This way hired programmers can easily work on your project without even seeing what they don't need to see while still being able to use what they need to use.</p>

Title: How to protect source code from remote developers?

Body:
My company is going to hire an external developer to create some new modules and fix some bugs in our PHP software.

We have never hired an external developer by the hour before. How can we protect the source code? We are not comfortable giving out source code and were thinking that everything remained under a surveillance enabled VPN which external developer would log in to.

Has anyone solved this problem before? If so, how?

Edit: We want the developer to see/modify the code but under surveillance and on our machine remotely. Does anybody have a similar setup?

Edit 2: NDA is just a formality. IMO, even people who are in favor of NDAs know that it'll do nothing to protect their property.

Edit 3: Let me clarify that we aren't worried about the developer copying an algorithm or a solution from the code. Code is coming out of his brain, so naturally he is the creator and he can create that again. But our code is built over several years with tens of developers working on it. Let's say I hire an incompetent programmer by mistake, who steals our years of work and then sells it to the competitor. That can make us lose our cutting edge. I know this is rare, but such a threat has to be taken under consideration if you're in business. I'll make points of my comments so its easy for everyone to communicate:

Why NDA sucks? Take this scenario, if anyone is capable of suggesting a solution to this scenario I will consider the NDA effective. Ok, here goes:
We hire 2 external developers, one of them sells our code as it is to someone else after a year. You are no longer in touch with any of the developers, how are you supposed to find out who ripped you off? NDA does provide a purpose, but you can't rely completely on that. At least we cannot.

I did not meant to offend anyone while I was posting this question, even though unintentionally I did. But again to people answering/commenting like 'I will never ever work with you' or that Men-in-black-gadget thingy: It's not about you, it's a thread about how feasible a given technical solution would be. And if anyone in this community has worked under such an environment.

About 'Trust', of course we won't hire anyone we do not trust. But is that it? Can't someone be deceitful at first? We all trusted a lot of politicians to run our country, did they not fail us ever? So, I'm saying 'trust' is a complete other layer of protection like NDA, and my question was not directed to it. My question is rather directed towards technical measures we can take to avoid such a thing from happening.


问:
Please explain the statement that the function an+b belongs to O(n^2) and Θ(n)?
Let's say I have a linear function f(n)= an+b, what is the best way to prove that this function belongs to O(n2) and Θ(n)?

I do not need mathematical rigor here. I need a programmers answer. Some logical way of explaining.

This is precisely why I didn't post the question in mathematics Q&A and instead in the Programmers Q&A.

答:
When you're dealing with polynomials, you only care about the degree of the polynomial. That is, for an + b, you only care about n. If it was an^3 + bn^2 + cn + d, you would only care about n^3.

So a polynomial with degree d will always be in Θ(n^d). Simple.

Now we need to talk about the difference between Θ and O. Essentially, it's the same difference as between == and <= respectively. So Θ(n) means that it is always within a constant factor of n. O(n) means that it is always either within a constant factor of n or less than n.

This means that any function in Θ(s), for any s, will also be in O(s). Also, if a function is in Θ(s) and s is always less than some other function t, that function is in O(t) but not Θ(t).

For the sake of completeness, there is also Ω(n). If Θ represents == and O represents <=, Ω represents >=. So an + b is in Ω(1), Θ(n) and O(n^2).

As I said earlier, it's really easy to figure out what class polynomials are in--you just look at the degree. There are some other functions that are easy to work with as well.

Any functions in the form of a^bn for arbitrary a and b are in Θ(a^n). For any value c >= a, they are in O(c^n). Every polynomial is in O(2^n). Essentially this just says that exponential functions always beat out polynomials and that the base of the exponential function matters.

Logarithms are the opposite. For one, log_b n is in Θ(log n) for any b. This means the base doesn't matter for logarithms. This makes sense because switching between different bases in logarithms is just multiplying by a constant. Logarithmic functions are also in O(n)--that is, a logarithmic function is smaller than any polynomial (at least of degree 1).

Given a sum of these functions, the biggest one "wins". So n + log n is in Θ(n) because the n term dominates the log n term. Multiplication is more complicated. For CS, the only thing you need to know is that nlog n is between n and n^2.

ContentLicense: CC BY-SA 3.0


问:
How to protect source code from remote developers?
My company is going to hire an external developer to create some new modules and fix some bugs in our PHP software.

We have never hired an external developer by the hour before. How can we protect the source code? We are not comfortable giving out source code and were thinking that everything remained under a surveillance enabled VPN which external developer would log in to.

Has anyone solved this problem before? If so, how?

Edit: We want the developer to see/modify the code but under surveillance and on our machine remotely. Does anybody have a similar setup?

Edit 2: NDA is just a formality. IMO, even people who are in favor of NDAs know that it'll do nothing to protect their property.

Edit 3: Let me clarify that we aren't worried about the developer copying an algorithm or a solution from the code. Code is coming out of his brain, so naturally he is the creator and he can create that again. But our code is built over several years with tens of developers working on it. Let's say I hire an incompetent programmer by mistake, who steals our years of work and then sells it to the competitor. That can make us lose our cutting edge. I know this is rare, but such a threat has to be taken under consideration if you're in business. I'll make points of my comments so its easy for everyone to communicate:

Why NDA sucks? Take this scenario, if anyone is capable of suggesting a solution to this scenario I will consider the NDA effective. Ok, here goes:
We hire 2 external developers, one of them sells our code as it is to someone else after a year. You are no longer in touch with any of the developers, how are you supposed to find out who ripped you off? NDA does provide a purpose, but you can't rely completely on that. At least we cannot.

I did not meant to offend anyone while I was posting this question, even though unintentionally I did. But again to people answering/commenting like 'I will never ever work with you' or that Men-in-black-gadget thingy: It's not about you, it's a thread about how feasible a given technical solution would be. And if anyone in this community has worked under such an environment.

About 'Trust', of course we won't hire anyone we do not trust. But is that it? Can't someone be deceitful at first? We all trusted a lot of politicians to run our country, did they not fail us ever? So, I'm saying 'trust' is a complete other layer of protection like NDA, and my question was not directed to it. My question is rather directed towards technical measures we can take to avoid such a thing from happening.

答:
If you are really that jumpy about allowing an external developer access to your source code, then just hire them to create the new modules, and fix the existing bugs yourself.

That way, the only code the outsider ever sees is the code she has written herself.


答:
The Big Oh notation (O, Theta, Omega) is about growth rates of functions.

When you implement an algorithm, it has a certain characteristic how the runtime changes when you increase the dataset operates on. Now, you may optimize the algorithm so it runs faster by a factor of 100. Sure, this is great, but essentially, it's still the same algorithm. Similarly, in a few years, computers may be twice as fast as they are today.

The Landau notation abstracts away these constant factors. It doesn't care about whether an algorithm f is always twice as fast as another algorithm g: Maybe g can be optimized to run 4 times faster, or you might be able to buy faster hardware instead. If you look at it from this perspective, you might say they are "the same". (That is not to say you can (always) ignore constant factors in practice.)

Big oh specifies an upper bound, it's similar to the <= relation.

You will agree that 1 < 2 is true. Does that mean that 1 cannot be less than any other number? Certainly not. There is an infinite amount of numbers that are bigger than 1.

With growth rates, it's similar. O(n) denotes the set of all functions, that grow linearly (or more slowly). O(n^2) on the other hand denotes all those functions, that grow with quadratic compelxity (or slower). I am sure that you will agree that a linear function grows more slowly than a quadratic function.

This is why  a function can be in more than one "Big-oh" class.

Here is a comparison of different functions with : (from Knuth's Concrete mathematics)

From left to right, functions grow faster.

Also, , meaning n^2 grows faster than n^1 because 2 > 1.

Definitions

"f grows faster or equally fast as g"

"f grows slower or equally fast as g"

The combination of the above two. It says the function f grows "equally fast" as g. It's an equivalence relation.

Interpretation

Let's say you have two algorithms, f and g.

Omega

Assuming ,  means that no matter your budget, there is no constant amount of computing power that you can add to your system, such that f will always run as fast as g.

Big oh

Assuming ,  means that if you have enough data, f will always run faster than g, no matter how much computing power you add to your system.

Proof

If you are really trying to prove this, you need to show using the definitions of the Landau notation that your function satisfies the necessary conditions.

So you need to find values for c, d, n_0 such that the condition holds.

Here is how you can do that for the lower bound with c:

It is important to realize, that me arbitrarily defining c as being smaller than a-1 is perfectly fine. The definition of Theta(g) says that "there exists a c". It can be any value as long as it is bigger than 0. (If a is a positive real number, you would need to change the proof slightly however, because a - 1 might actually be negative)

(I am assuming a to be positive, otherwise the function will always be negative for big values of n, which makes no sense for a function denoting the runtime.)

You can try doing it for the upper bound, it's quite similar. If you don't know how, I can provide a proof for you.

Hint: start with d > a + 1

Attention

It is important that you do not prove it the wrong way around. If you assume that (an + b) is in O(n) and go from there, you have not proven what you wanted. You will need to verify that all of your steps go both way, i.e. instead of => you have <=>.

Title: Please explain the statement that the function an+b belongs to O(n^2) and Θ(n)?

Body:
Let's say I have a linear function f(n)= an+b, what is the best way to prove that this function belongs to O(n2) and Θ(n)?

I do not need mathematical rigor here. I need a programmers answer. Some logical way of explaining.

This is precisely why I didn't post the question in mathematics Q&A and instead in the Programmers Q&A.


问:
Is functional spec a "design document"?
So I have been a bit lost in the terms, so first of all I present you what I have learned so far:

System requirements specification - what users want, what the system should do
Functional requirement - how the things, which users want, will actually work in the application

Also I would say that the latter is a design document. Is that right or is there another document in addition to these?

答:
Functional specification is a design document - describes exactly the functionality of the system. What John Bode suggest is something else, system specification in OP's context means a specification of the software system, done by business analyst.
System requirements specification describes the functionality of the system as wanted by users.

Title: Is functional spec a "design document"?


问:
What is the structure of a team developing a computer game?
I wanted to ask if there is a typical structure for a team developing a computer game and, if so, what are the specific roles of the team members.

Also, what is the size of such a team (in terms of order of magnitude, 5-10? 10-100? more?).

Is there any literature on this topic?

答:
There are many different kinds of computer games and, correspondingly, many different appropriate sizes and structures of development teams. Some examples:

A simple game can be developed by a single idealistic amateur or hopeful indie game developer who does everything, perhaps outsourcing graphics and sound. Many mobile games are of this type. I believe Minecraft started out like this.

A somewhat more complex game at a small development company may be developed by a team consisting of one or two graphics guys, two or three developers (perhaps dividing work into frontend and backend), one game designer and one project manager (the latter roles may be part time or done by the same person). Most indie and mobile as well as many Facebook games are done on this scale.

A "triple A" title, the kind of game that has TV ads and sells millions of copies, will nowadays be developed by a team of up to 300 people with multiple levels of hierarchy for each area (game design, graphics, sound, coding, testing, infrastructure, overall project management) and highly specialized roles. Racing games have dedicated full-time car designers, for example.

Simply run some games you like and look at their credits to get a look at the structure of the development team - most will list individual roles.


问:
Does Silverlight have a future?
Recently I have read some articles/blogs/comments about the development and history of WPF and Silverlight. In some forums many developers and users criticize the performance of WPF applications (for example Visual Studio 2010). Actually the market share of Silverlight in comparison to Flash is not very high. At PDC 2010 Bob Muglia said something like "our Silverlight strategy and focus going forward has shifted...." and Microsoft wants to push HTML5 in the future.

Additionally, Microsoft has announced HTML5 being a core part of the Windows 8 and Windows Phone 8 ("Mango") platforms.

Recently I have started learning Silverlight and now I must ask myself, if I should continue investing time in learning these (in my opinions) very nice and powerful technologies!? Does they have a future? Does (Windows) desktop (client) applications have a future? Does so called "Rich Internet Applications" have a future? Or will HTML5 become the "absolute truth" in software development?

What is your opinion and what do you think?

答: I think many people look at Microsoft and they see one gigantic entity. That's not really how it is, though. Microsoft is more like dozens of small teams and it's really only the name "Microsoft" that ties them together. So while the IE team is focusing on HTML 5 and pushing that as much as they can, you can bet the WPF/Sliverlight team is just as hard at work on WPF and Silverlight.</p>

Title: Does Silverlight have a future?

ContentLicense: CC BY-SA 2.5


问:
Pros and Cons of holding all the business logic in stored procedures in web application
In some organization I worked for web applications are developed basing all the business logic in Database stored procedures. For example, use html for view and servlet as controllers to divert the client request to appropriate Database stored procedures.

What are the advantages and disadvantages of this kind of designs? In my opinion if the business logic highly depends on the database than better follow this kind of design!!!!!

答:
In the modern age this isn't really a common approach anymore.  There was a time that putting business logic in stored procedures was a common thing to do early in web programming because the alternatives where few and often difficult to use. Today I would recommend against it.

I would have to say in 2012 there is nothing about business logic in stored procedures that could be justified as somehow a choice having beat out other approaches after having weighed the pro's and cons's.  Any PRO points would be academic at best.

CON's
It's not linq code.  The future of TSQL is compiled linq, mine as well start to learn it.

Compiled code is more stable and easier to work with.  If I'm debugging something there is so much information available if I used C# or Java.

Stored procedures are likely to end up with too many responsibilities, it's a best practice to try to keep your responsibilities to 1.

Lack of separation of responsibilities will lead to an application that just gets harder and harder to work on and less and less stable as it's core classes just get bigger and bigger.

If you like Microsoft Asp.Net MVC combined with Entity Framework Code First will allow you to rapidly build any application and you won't need any stored procedures.


问:
Convert from Procedural to Object Oriented Code
I have been reading Working Effectively with Legacy Code and Clean Code with the goal of learning strategies on how to begin cleaning up the existing code-base of a large ASP.NET webforms application.

This system has been around since 2005 and since then has undergone a number of enhancements.  Originally the code was structured as follows (and is still largely structured this way):

ASP.NET (aspx/ascx)

Code-behind (c#)

Business Logic Layer (c#)

Data Access Layer (c#)

Database (Oracle)

The main issue is that the code is procedural masquerading as object-oriented.  It virtually violates all of the guidelines described in both books.

This is an example of a typical class in the Business Logic Layer:

```<code>    public class AddressBO
{
    public TransferObject GetAddress(string addressID)
    {
        if (StringUtils.IsNull(addressID))
        {
            throw new ValidationException("Address ID must be entered");
        }

        AddressDAO addressDAO = new AddressDAO();
        return addressDAO.GetAddress(addressID);
    }

    public TransferObject Insert(TransferObject addressDetails)
    {
        if (StringUtils.IsNull(addressDetails.GetString("EVENT_ID")) ||
            StringUtils.IsNull(addressDetails.GetString("LOCALITY")) ||
            StringUtils.IsNull(addressDetails.GetString("ADDRESS_TARGET")) ||
            StringUtils.IsNull(addressDetails.GetString("ADDRESS_TYPE_CODE")) ||
            StringUtils.IsNull(addressDetails.GetString("CREATED_BY")))
        {
            throw new ValidationException(
                "You must enter an Event ID, Locality, Address Target, Address Type Code and Created By.");
        }

        string addressID = Sequence.GetNextValue("ADDRESS_ID_SEQ");
        addressDetails.SetValue("ADDRESS_ID", addressID);

        string syncID = Sequence.GetNextValue("SYNC_ID_SEQ");
        addressDetails.SetValue("SYNC_ADDRESS_ID", syncID);

        TransferObject syncDetails = new TransferObject();

        Transaction transaction = new Transaction();

        try
        {
            AddressDAO addressDAO = new AddressDAO();
            addressDAO.Insert(addressDetails, transaction);

            // insert the record for the target
            TransferObject addressTargetDetails = new TransferObject();
            switch (addressDetails.GetString("ADDRESS_TARGET"))
            {
                case "PARTY_ADDRESSES":
                    {
                        addressTargetDetails.SetValue("ADDRESS_ID", addressID);
                        addressTargetDetails.SetValue("ADDRESS_TYPE_CODE",
                                                      addressDetails.GetString("ADDRESS_TYPE_CODE"));
                        addressTargetDetails.SetValue("PARTY_ID", addressDetails.GetString("PARTY_ID"));
                        addressTargetDetails.SetValue("EVENT_ID", addressDetails.GetString("EVENT_ID"));
                        addressTargetDetails.SetValue("CREATED_BY", addressDetails.GetString("CREATED_BY"));

                        addressDAO.InsertPartyAddress(addressTargetDetails, transaction);

                        break;
                    }
                case "PARTY_CONTACT_ADDRESSES":
                    {
                        addressTargetDetails.SetValue("ADDRESS_ID", addressID);
                        addressTargetDetails.SetValue("ADDRESS_TYPE_CODE",
                                                      addressDetails.GetString("ADDRESS_TYPE_CODE"));
                        addressTargetDetails.SetValue("PUBLIC_RELEASE_FLAG",
                                                      addressDetails.GetString("PUBLIC_RELEASE_FLAG"));
                        addressTargetDetails.SetValue("CONTACT_ID", addressDetails.GetString("CONTACT_ID"));
                        addressTargetDetails.SetValue("EVENT_ID", addressDetails.GetString("EVENT_ID"));
                        addressTargetDetails.SetValue("CREATED_BY", addressDetails.GetString("CREATED_BY"));

                        addressDAO.InsertContactAddress(addressTargetDetails, transaction);

                        break;
                    }

                << many more cases here >>
                default:
                    {
                        break;
                    }
            }

            // synchronise
            SynchronisationBO synchronisationBO = new SynchronisationBO();
            syncDetails = synchronisationBO.Synchronise("I", transaction,
                                                        "ADDRESSES", addressDetails.GetString("ADDRESS_TARGET"),
                                                        addressDetails, addressTargetDetails);

            // commit
            transaction.Commit();
        }
        catch (Exception)
        {
            transaction.Rollback();
            throw;
        }

        return new TransferObject("ADDRESS_ID", addressID, "SYNC_DETAILS", syncDetails);
    }

    << many more methods are here >>

}
</code>```

It has a lot of duplication, the class has a number of responsibilities, etc, etc - it is just generally 'un-clean' code.

All of the code throughout the system is dependent on concrete implementations.

This is an example of a typical class in the Data Access Layer:

```<code>    public class AddressDAO : GenericDAO
{
    public static readonly string BASE_SQL_ADDRESSES =
        "SELECT " +
        "  a.address_id, " +
        "  a.event_id, " +
        "  a.flat_unit_type_code, " +
        "  fut.description as flat_unit_description, " +
        "  a.flat_unit_num, " +
        "  a.floor_level_code, " +
        "  fl.description as floor_level_description, " +
        "  a.floor_level_num, " +
        "  a.building_name, " +
        "  a.lot_number, " +
        "  a.street_number, " +
        "  a.street_name, " +
        "  a.street_type_code, " +
        "  st.description as street_type_description, " +
        "  a.street_suffix_code, " +
        "  ss.description as street_suffix_description, " +
        "  a.postal_delivery_type_code, " +
        "  pdt.description as postal_delivery_description, " +
        "  a.postal_delivery_num, " +
        "  a.locality, " +
        "  a.state_code, " +
        "  s.description as state_description, " +
        "  a.postcode, " +
        "  a.country, " +
        "  a.lock_num, " +
        "  a.created_by, " +
        "  TO_CHAR(a.created_datetime, '" + SQL_DATETIME_FORMAT + "') as created_datetime, " +
        "  a.last_updated_by, " +
        "  TO_CHAR(a.last_updated_datetime, '" + SQL_DATETIME_FORMAT + "') as last_updated_datetime, " +
        "  a.sync_address_id, " +
        "  a.lat," +
        "  a.lon, " +
        "  a.validation_confidence, " +
        "  a.validation_quality, " +
        "  a.validation_status " +
        "FROM ADDRESSES a, FLAT_UNIT_TYPES fut, FLOOR_LEVELS fl, STREET_TYPES st, " +
        "     STREET_SUFFIXES ss, POSTAL_DELIVERY_TYPES pdt, STATES s " +
        "WHERE a.flat_unit_type_code = fut.flat_unit_type_code(+) " +
        "AND   a.floor_level_code = fl.floor_level_code(+) " +
        "AND   a.street_type_code = st.street_type_code(+) " +
        "AND   a.street_suffix_code = ss.street_suffix_code(+) " +
        "AND   a.postal_delivery_type_code = pdt.postal_delivery_type_code(+) " +
        "AND   a.state_code = s.state_code(+) ";

    public TransferObject GetAddress(string addressID)
    {
        //Build the SELECT Statement
        StringBuilder selectStatement = new StringBuilder(BASE_SQL_ADDRESSES);

        //Add WHERE condition
        selectStatement.Append(" AND a.address_id = :addressID");

        ArrayList parameters = new ArrayList{DBUtils.CreateOracleParameter("addressID", OracleDbType.Decimal, addressID)};

        // Execute the SELECT statement
        Query query = new Query();
        DataSet results = query.Execute(selectStatement.ToString(), parameters);

        // Check if 0 or more than one rows returned
        if (results.Tables[0].Rows.Count == 0)
        {
            throw new NoDataFoundException();
        }
        if (results.Tables[0].Rows.Count > 1)
        {
            throw new TooManyRowsException();
        }

        // Return a TransferObject containing the values
        return new TransferObject(results);
    }

    public void Insert(TransferObject insertValues, Transaction transaction)
    {
        // Store Values
        string addressID = insertValues.GetString("ADDRESS_ID");
        string syncAddressID = insertValues.GetString("SYNC_ADDRESS_ID");
        string eventID = insertValues.GetString("EVENT_ID");
        string createdBy = insertValues.GetString("CREATED_BY");

        // postal delivery
        string postalDeliveryTypeCode = insertValues.GetString("POSTAL_DELIVERY_TYPE_CODE");
        string postalDeliveryNum = insertValues.GetString("POSTAL_DELIVERY_NUM");

        // unit/building
        string flatUnitTypeCode = insertValues.GetString("FLAT_UNIT_TYPE_CODE");
        string flatUnitNum = insertValues.GetString("FLAT_UNIT_NUM");
        string floorLevelCode = insertValues.GetString("FLOOR_LEVEL_CODE");
        string floorLevelNum = insertValues.GetString("FLOOR_LEVEL_NUM");
        string buildingName = insertValues.GetString("BUILDING_NAME");

        // street
        string lotNumber = insertValues.GetString("LOT_NUMBER");
        string streetNumber = insertValues.GetString("STREET_NUMBER");
        string streetName = insertValues.GetString("STREET_NAME");
        string streetTypeCode = insertValues.GetString("STREET_TYPE_CODE");
        string streetSuffixCode = insertValues.GetString("STREET_SUFFIX_CODE");

        // locality/state/postcode/country
        string locality = insertValues.GetString("LOCALITY");
        string stateCode = insertValues.GetString("STATE_CODE");
        string postcode = insertValues.GetString("POSTCODE");
        string country = insertValues.GetString("COUNTRY");

        // esms address
        string esmsAddress = insertValues.GetString("ESMS_ADDRESS");

        //address/GPS
        string lat = insertValues.GetString("LAT");
        string lon = insertValues.GetString("LON");
        string zoom = insertValues.GetString("ZOOM");

        //string validateDate = insertValues.GetString("VALIDATED_DATE");
        string validatedBy = insertValues.GetString("VALIDATED_BY");
        string confidence = insertValues.GetString("VALIDATION_CONFIDENCE");
        string status = insertValues.GetString("VALIDATION_STATUS");
        string quality = insertValues.GetString("VALIDATION_QUALITY");

        // the insert statement
        StringBuilder insertStatement = new StringBuilder("INSERT INTO ADDRESSES (");
        StringBuilder valuesStatement = new StringBuilder("VALUES (");

        ArrayList parameters = new ArrayList();

        // build the insert statement
        insertStatement.Append("ADDRESS_ID, EVENT_ID, CREATED_BY, CREATED_DATETIME, LOCK_NUM ");
        valuesStatement.Append(":addressID, :eventID, :createdBy, SYSDATE, 1 ");
        parameters.Add(DBUtils.CreateOracleParameter("addressID", OracleDbType.Decimal, addressID));
        parameters.Add(DBUtils.CreateOracleParameter("eventID", OracleDbType.Decimal, eventID));
        parameters.Add(DBUtils.CreateOracleParameter("createdBy", OracleDbType.Varchar2, createdBy));

        // build the insert statement
        if (!StringUtils.IsNull(syncAddressID))
        {
            insertStatement.Append(", SYNC_ADDRESS_ID");
            valuesStatement.Append(", :syncAddressID");
            parameters.Add(DBUtils.CreateOracleParameter("syncAddressID", OracleDbType.Decimal, syncAddressID));
        }

        if (!StringUtils.IsNull(postalDeliveryTypeCode))
        {
            insertStatement.Append(", POSTAL_DELIVERY_TYPE_CODE");
            valuesStatement.Append(", :postalDeliveryTypeCode ");
            parameters.Add(DBUtils.CreateOracleParameter("postalDeliveryTypeCode", OracleDbType.Varchar2, postalDeliveryTypeCode));
        }

        if (!StringUtils.IsNull(postalDeliveryNum))
        {
            insertStatement.Append(", POSTAL_DELIVERY_NUM");
            valuesStatement.Append(", :postalDeliveryNum ");
            parameters.Add(DBUtils.CreateOracleParameter("postalDeliveryNum", OracleDbType.Varchar2, postalDeliveryNum));
        }

        if (!StringUtils.IsNull(flatUnitTypeCode))
        {
            insertStatement.Append(", FLAT_UNIT_TYPE_CODE");
            valuesStatement.Append(", :flatUnitTypeCode ");
            parameters.Add(DBUtils.CreateOracleParameter("flatUnitTypeCode", OracleDbType.Varchar2, flatUnitTypeCode));
        }

        if (!StringUtils.IsNull(lat))
        {
            insertStatement.Append(", LAT");
            valuesStatement.Append(", :lat ");
            parameters.Add(DBUtils.CreateOracleParameter("lat", OracleDbType.Decimal, lat));
        }

        if (!StringUtils.IsNull(lon))
        {
            insertStatement.Append(", LON");
            valuesStatement.Append(", :lon ");
            parameters.Add(DBUtils.CreateOracleParameter("lon", OracleDbType.Decimal, lon));
        }

        if (!StringUtils.IsNull(zoom))
        {
            insertStatement.Append(", ZOOM");
            valuesStatement.Append(", :zoom ");
            parameters.Add(DBUtils.CreateOracleParameter("zoom", OracleDbType.Decimal, zoom));
        }

        if (!StringUtils.IsNull(flatUnitNum))
        {
            insertStatement.Append(", FLAT_UNIT_NUM");
            valuesStatement.Append(", :flatUnitNum ");
            parameters.Add(DBUtils.CreateOracleParameter("flatUnitNum", OracleDbType.Varchar2, flatUnitNum));
        }

        if (!StringUtils.IsNull(floorLevelCode))
        {
            insertStatement.Append(", FLOOR_LEVEL_CODE");
            valuesStatement.Append(", :floorLevelCode ");
            parameters.Add(DBUtils.CreateOracleParameter("floorLevelCode", OracleDbType.Varchar2, floorLevelCode));
        }

        if (!StringUtils.IsNull(floorLevelNum))
        {
            insertStatement.Append(", FLOOR_LEVEL_NUM");
            valuesStatement.Append(", :floorLevelNum ");
            parameters.Add(DBUtils.CreateOracleParameter("floorLevelNum", OracleDbType.Varchar2, floorLevelNum));
        }

        if (!StringUtils.IsNull(buildingName))
        {
            insertStatement.Append(", BUILDING_NAME");
            valuesStatement.Append(", :buildingName ");
            parameters.Add(DBUtils.CreateOracleParameter("buildingName", OracleDbType.Varchar2, buildingName));
        }

        if (!StringUtils.IsNull(lotNumber))
        {
            insertStatement.Append(", LOT_NUMBER");
            valuesStatement.Append(", :lotNumber ");
            parameters.Add(DBUtils.CreateOracleParameter("lotNumber", OracleDbType.Varchar2, lotNumber));
        }

        if (!StringUtils.IsNull(streetNumber))
        {
            insertStatement.Append(", STREET_NUMBER");
            valuesStatement.Append(", :streetNumber ");
            parameters.Add(DBUtils.CreateOracleParameter("streetNumber", OracleDbType.Varchar2, streetNumber));
        }

        if (!StringUtils.IsNull(streetName))
        {
            insertStatement.Append(", STREET_NAME");
            valuesStatement.Append(", :streetName ");
            parameters.Add(DBUtils.CreateOracleParameter("streetName", OracleDbType.Varchar2, streetName));
        }

        if (!StringUtils.IsNull(streetTypeCode))
        {
            insertStatement.Append(", STREET_TYPE_CODE");
            valuesStatement.Append(", :streetTypeCode ");
            parameters.Add(DBUtils.CreateOracleParameter("streetTypeCode", OracleDbType.Varchar2, streetTypeCode));
        }

        if (!StringUtils.IsNull(streetSuffixCode))
        {
            insertStatement.Append(", STREET_SUFFIX_CODE");
            valuesStatement.Append(", :streetSuffixCode ");
            parameters.Add(DBUtils.CreateOracleParameter("streetSuffixCode", OracleDbType.Varchar2, streetSuffixCode));
        }

        if (!StringUtils.IsNull(locality))
        {
            insertStatement.Append(", LOCALITY");
            valuesStatement.Append(", :locality");
            parameters.Add(DBUtils.CreateOracleParameter("locality", OracleDbType.Varchar2, locality));
        }

        if (!StringUtils.IsNull(stateCode))
        {
            insertStatement.Append(", STATE_CODE");
            valuesStatement.Append(", :stateCode");
            parameters.Add(DBUtils.CreateOracleParameter("stateCode", OracleDbType.Varchar2, stateCode));
        }

        if (!StringUtils.IsNull(postcode))
        {
            insertStatement.Append(", POSTCODE");
            valuesStatement.Append(", :postcode ");
            parameters.Add(DBUtils.CreateOracleParameter("postcode", OracleDbType.Varchar2, postcode));
        }

        if (!StringUtils.IsNull(country))
        {
            insertStatement.Append(", COUNTRY");
            valuesStatement.Append(", :country ");
            parameters.Add(DBUtils.CreateOracleParameter("country", OracleDbType.Varchar2, country));
        }

        if (!StringUtils.IsNull(esmsAddress))
        {
            insertStatement.Append(", ESMS_ADDRESS");
            valuesStatement.Append(", :esmsAddress ");
            parameters.Add(DBUtils.CreateOracleParameter("esmsAddress", OracleDbType.Varchar2, esmsAddress));
        }

        if (!StringUtils.IsNull(validatedBy))
        {
            insertStatement.Append(", VALIDATED_DATE");
            valuesStatement.Append(", SYSDATE ");
            insertStatement.Append(", VALIDATED_BY");
            valuesStatement.Append(", :validatedBy ");
            parameters.Add(DBUtils.CreateOracleParameter("validatedBy", OracleDbType.Varchar2, validatedBy));
        }

        if (!StringUtils.IsNull(confidence))
        {
            insertStatement.Append(", VALIDATION_CONFIDENCE");
            valuesStatement.Append(", :confidence ");
            parameters.Add(DBUtils.CreateOracleParameter("confidence", OracleDbType.Decimal, confidence));
        }

        if (!StringUtils.IsNull(status))
        {
            insertStatement.Append(", VALIDATION_STATUS");
            valuesStatement.Append(", :status ");
            parameters.Add(DBUtils.CreateOracleParameter("status", OracleDbType.Varchar2, status));
        }

        if (!StringUtils.IsNull(quality))
        {
            insertStatement.Append(", VALIDATION_QUALITY");
            valuesStatement.Append(", :quality ");
            parameters.Add(DBUtils.CreateOracleParameter("quality", OracleDbType.Decimal, quality));
        }

        // finish off the statement
        insertStatement.Append(") ");
        valuesStatement.Append(")");

        // build the insert statement
        string sql = insertStatement + valuesStatement.ToString();

        // Execute the INSERT Statement
        Dml dmlDAO = new Dml();
        int rowsAffected = dmlDAO.Execute(sql, transaction, parameters);

        if (rowsAffected == 0)
        {
            throw new NoRowsAffectedException();
        }
    }

    << many more methods go here >>
}
</code>```

This system was developed by me and a small team back in 2005 after a 1 week .NET course.  Before than my experience was in client-server applications.  Over the past 5 years I've come to recognise the benefits of automated unit testing, automated integration testing and automated acceptance testing (using Selenium or equivalent) but the current code-base seems impossible to introduce these concepts.

We are now starting to work on a major enhancement project with tight time-frames.  The team consists of 5 .NET developers - 2 developers with a few years of .NET experience and 3 others with little or no .NET experience.  None of the team (including myself) has experience in using .NET unit testing or mocking frameworks.

What strategy would you use to make this code cleaner, more object-oriented, testable and maintainable?

答:
Those are both good books.  If your going to start rewriting code in that manner I think it's important to also begin to cover the code with unit tests to help keep it stable as you rewrite it.

It has to be done in small steps and modifying that kind of code can easily destabilize the entire system.

I would not modify any code you are not actively working on.  Only do this on code you are actively enhancing or fixing.  If something is serving it's purpose but hasn't been modified in years then just leave it.  It's doing it's thing even if you know a better way.

At the end of the day the company needs productivity.  While better code increases productivity rewriting code just cause it could be written better is probably not the best way to bring value to your product.


问:
Do some best practices depend on skill?
Is there evidence that some software development best practices depend on programming skill level? I mean, these methods are good, but maybe the way the are used or the extent might vary?

This question arose after I read Paul Graham's commentary about OOP, and the last bullet point of this accepted answer. It proposes that where, how, and how much to use unit tests might depend on your programming skill.

So do top programmers use different approaches than average programmers?

答:
From PG's blog entry:

There is a danger in designing a language based on one's own experience of programming. But it seems more dangerous to put stuff in that you've never needed because it's thought to be a good idea.

With regard to your question, I'd offer the following:

There is a danger in solving programming problems with seemingly boring boilerplate code. But it seems more dangerous to program in ways that you never have before simply because it's thought to be a good idea.

For example, here's what I observed with .NET:

When .NET 2.0 shipped, junior developers used generics in ways that did not make sense, simply because they thought they were a good idea.

When .NET 3.5 shipped, junior developers wrote confusing LINQ statements in places where simple foreach loops would suffice simply because they thought they were a good idea.

When ASP.NET Web Forms fell out of favor with the development community, junior developers a fellow junior developer added new features according to an MVP Pattern simply because he read that it was a good idea.

To make it perfectly clear, Generics, LINQ, and the MVP Pattern all have their place. When used correctly, these can simplify code; but they must be used in the proper context.

Title: Do some best practices depend on skill?


问:
Advice for solo programmer whose team will expand in the near future
For 4 years now, I've been the solo developer for a small company. We have a handful of well establish products in a niche industry. We will be hiring 1-2 developers soon, and that will likely change the way things operate around here.

While I won't have a "real" title, I will be "in charge" of this team. What I want to do is establish a very organized and productive programming department for my company. I got this solo job right out of college, so while I've become proficient as a programmer in this industry, I lack a lot of team programming experience. I feel that starting out on the right foot will be key.

Right now it's just me, a few computers, and an SVN server. I'm looking for any general guidance on building a team from the ground up.

答:
This is very similar to the situation I was in a few months ago.  The best advice I can give is drop the typical hubris of being a programmer and hire the best of the best your company can afford.

I was "in charge" for a while, but a team member with more experience stepped up and I gladly relinquished my administrative duties so I could do what I'm best at, writing quality code.  I'm still a mentor to the team as you will be.

If you do what's best for the company in this situation, you will be rewarded.


问:
How to avoid typo errors, etc?
For the first time I have been coding for an open-source software where all my work gets reviewed before being commited. I understand reviewing work isn't an easy task, so I don't like to waste reviewers' time and effort. But many times I make silly typo errors and errors of other kind while making a change in the code.

For example, the last time when I refactored some old code I moved code from one class to another, but forgot to check that $this only worked in the old class and needed to be changed now.

I do run unit tests, but sometime they miss these errors (we have incomplete test coverage right now). And I agree that many times I am in a hurry to submit the change only to get the work done faster.

But, besides wasting reviewers' time, this actually slows down the development process and reduces my credibility (small errors may even hide praise for good work).

What's the best way to avoid such a scenario or, in other words, how can I review my own code before someone else does?

Edit: I use Notepad++ for PHP, please don't ask me to change the IDE right-away; however, suggestions are welcome if they are persuasive ;)

答: I kept making similar silly mistakes. The solution I found was unit testing. You set up a series of automated tests to check the correctness of your code as you write it. </p>

Title: How to avoid typo errors, etc?


答:
I do run tests, but sometime they miss these errors (incomplete test coverage).

After your error is discovered, consider adding a new test that would prevent future contributors from repeating this error or better yet, whole kind of errors like this.

If done right, improving test coverage and regression testing will likely sufficiently compensate the damage done by your mistake.

Title: How to avoid typo errors, etc?

Body:
For the first time I have been coding for an open-source software where all my work gets reviewed before being commited. I understand reviewing work isn't an easy task, so I don't like to waste reviewers' time and effort. But many times I make silly typo errors and errors of other kind while making a change in the code.

For example, the last time when I refactored some old code I moved code from one class to another, but forgot to check that $this only worked in the old class and needed to be changed now.

I do run unit tests, but sometime they miss these errors (we have incomplete test coverage right now). And I agree that many times I am in a hurry to submit the change only to get the work done faster.

But, besides wasting reviewers' time, this actually slows down the development process and reduces my credibility (small errors may even hide praise for good work).

What's the best way to avoid such a scenario or, in other words, how can I review my own code before someone else does?

Edit: I use Notepad++ for PHP, please don't ask me to change the IDE right-away; however, suggestions are welcome if they are persuasive ;)


答:
Cons:

The database is the least scalable part of your architecture.

Especially in an age of web services and REST-ful 3rd party web applications, you won't be able to contain all of your business logic in stored procs.

SQL implementations vary, some can be tricky, and none read as fluidly as a first-class application-layer programming language.

Remember that code is read much more often than it is written.

Title: Pros and Cons of holding all the business logic in stored procedures in web application

Body:
In some organization I worked for web applications are developed basing all the business logic in Database stored procedures. For example, use html for view and servlet as controllers to divert the client request to appropriate Database stored procedures.

What are the advantages and disadvantages of this kind of designs? In my opinion if the business logic highly depends on the database than better follow this kind of design!!!!!

ContentLicense: CC BY-SA 4.0


答:
- Common sense approach would be taking your time and re-visiting your code before marking your work done. In addition, try to maximize your focus/concentration for the peace of work that you are assigned to do.

- First practical approach would be using re-factoring tools like JustCode or similar once. They would improve your productivity and you may tune it up for syntax errors.

- Second practical approach would be using TDD approach.
It will make sure that your code has proper tests to function (pass all required unit tests), otherwise it will fail.

Although, TDD takes time to implement and refactor existing code as needed, it is a clean way to write a reliable and solid code.

Title: How to avoid typo errors, etc?


答:
You have already answered your question by yourself.

There are several things that one should always remember when developing (no matter what language, IDE, project is on your desk):

- When developing, try to think only about the project you're working on. Everything else should be forgotten for a while, including the praise you'll get if you do your work well. Such thoughts will only distract you, and you'll make more mistakes as result.

- Don't hurry, if it isn't vital for the project. Take your time, try to test everything properly. As you mentioned, the fast-written but full-of-bugs code is not something to be proud of. I'm sure if you don't hurry so much you'll be able to detect many bugs by yourself.

And, as mentioned in other answers, run unit tests. And one more. There will ALWAYS be bugs. No one is perfect. But these two rules will help you reduce their quantity.

Title: How to avoid typo errors, etc?


答:
Write your code in a compiled language.

EDIT: I'm not proposing that this is a bullet-proof solution, but it will certainly help you to avoid many typos.

Title: How to avoid typo errors, etc?


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答: When all you have is a hammer, everything starts to look like a nail

LastEditorDisplayName: Roger Pate


答:
Without using much math, you take the function f(n)= an+b and drop all the constants, so it looks like this f(n)= n, then you take the "n" with the highest degree as your answer
Q.E.D Θ(n)</p>


问:
What does the term "Payload" mean in programming
I was going through the source code of an open source framework, where I saw a variable "payload" mentioned many times. Any ideas what "payload" stands for?</p>

答:
I have met two meanings of Payload so far:

1) The essential data that is being carried within a packet or other transmission unit. The payload does not include the "overhead" data required to get the packet to its destination. Note that what constitutes the payload may depend on the point-of-view. To a communications layer that needs some of the overhead data to do its job, the payload is sometimes considered to include the part of the overhead data that this layer handles. However, in more general usage, the payload is the bits that get delivered to the end user at the destination.

2) The eventual effect of a software virus that has been delivered to a user's computer.


答:
The term 'payload' is used to distinguish between the 'interesting' information in a chunk of data or similar, and the overhead to support it. It is borrowed from transportation, where it refers to the part of the load that 'pays': for example, a tanker truck may carry 20 tons of oil, but the fully loaded vehicle weighs much more than that - there's the vehicle itself, the driver, fuel, the tank, etc. It costs money to move all these, but the customer only cares about (and pays for) the oil, hence, 'pay-load'.

In programming, the most common usage of the term is in the context of message protocols, to differentiate the protocol overhead from the actual data. Take, for example, a JSON web service response that might look like this (formatted for readability):

```<code>{
    "status":"OK",
    "data":
        {
            "message":"Hello, world!"
        }
}
</code>```

In this example, the string Hello, world! is the payload, the part that the recipient is interested in; the rest, while vital information, is protocol overhead.

Another notable use of the term is in malware. Malicious software usually has two objectives: spreading itself, and performing some kind of modification on the target system (delete files, compromise system security, call home, etc.). The spreading part is the overhead, while the code that does the actual evil-doing is the payload.

Title: What does the term "Payload" mean in programming

Body: I was going through the source code of an open source framework, where I saw a variable "payload" mentioned many times. Any ideas what "payload" stands for?</p>

Body:
The term 'payload' is used to distinguish between the 'interesting' information in a chunk of data or similar, and the overhead to support it. It is borrowed from transportation, where it refers to the part of the load that 'pays': for example, a tanker truck may carry 20 tons of oil, but the fully loaded vehicle weighs much more than that - there's the vehicle itself, the driver, fuel, the tank, etc. It costs money to move all these, but the customer only cares about (and pays for) the oil, hence, 'pay-load'.

In programming, the most common usage of the term is in the context of message protocols, to differentiate the protocol overhead from the actual data. Take, for example, a JSON web service response that might look like this (formatted for readability):

{
    "status":"OK",
    "data":
        {
            "message":"Hello, world!"
        }
}

In this example, the string Hello, world! is the payload, the part that the recipient is interested in; the rest, while vital information, is protocol overhead.

Another notable use of the term is in malware. Malicious software usually has two objectives: spreading itself, and performing some kind of modification on the target system (delete files, compromise system security, call home, etc.). The spreading part is the overhead, while the code that does the actual evil-doing is the payload.


问:
Confusion regarding def function within Python
I've been learning Python for about 2 months now (Started with Learn Python The Hard Way, now reading Dive Into Python), and within both books, I still seem to be confused over this one bit of code.

Lets just take the default code that Dive Into Python uses as an example:

```<code>def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim",
                "database":"master",
                "uid":"sa",
                "pwd":"secret"
               }

print buildConnectionString(myParams)
</code>```

How does the function buildConnectionString with the argument (params) know to get its data from the variable myParams?  Or params.items(), too within the return line?  Wouldn't the argument in buildConnectionString need to be set as buildConnectionString(myParams) in order for it to read properly?  How can you set the variable of your data to myParams, but have the argument of your function be params and have it read?  How does it know to read myParams as params?

And is there a reason behind not naming your variable params, or vice versa naming your argument in your function myParams?  It's just been extremely confusing seeing the argument set as one word, and then having the variable named something completely different, but having the function still be able to read your code, even when the argument name is different from your variable with the data you're printing from.

答:
If we take a look at

```<code>def buildConnectionString(params):
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
</code>```

params is a locally-scoped variable. It's not referring to any other variables in your code, it is the name for the variable you pass into your function. What this means is that you can pass any variable into buildConnectionString() without having to know in advance what you are passing in.

Regarding naming myParams vs params there is no real reason. You could just as easily name it params if it helps you keep track of things. But what happens when you need to keep two sets of params variables? This is why you pass variables into your function rather than referencing global (defined outside of a function) variables. You could have written that function as

```<code>myParams = {"server":"mpilgrim",
            "database":"master",
            "uid":"sa",
            "pwd":"secret"
           }

def buildConnectionString():
    return ";".join(["%s=%s" % (k, v) for k, v in myParams.items()])

print buildConnectionString(myParams)
</code>```

Doing it that way means you can only print myParams. But if you define myOtherParams you couldn't print it at all. You just have to keep in mind that any variables defined inside of the parentheses is only a copy of the variable you pass into it, not the original variable itself.

Body:
If we take a look at

def buildConnectionString(params):
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

params is a locally-scoped variable. It's not referring to any other variables in your code, it is the name for the variable you pass into your function. What this means is that you can pass any variable into buildConnectionString() without having to know in advance what you are passing in.

Regarding naming myParams vs params there is no real reason. You could just as easily name it params if it helps you keep track of things. But what happens when you need to keep two sets of params variables? This is why you pass variables into your function rather than referencing global (defined outside of a function) variables. You could have written that function as

myParams = {"server":"mpilgrim",
            "database":"master",
            "uid":"sa",
            "pwd":"secret"
           }

def buildConnectionString():
    return ";".join(["%s=%s" % (k, v) for k, v in myParams.items()])

print buildConnectionString(myParams)

Doing it that way means you can only print myParams. But if you define myOtherParams you couldn't print it at all. You just have to keep in mind that any variables defined inside of the parentheses is only a copy of the variable you pass into it, not the original variable itself.


问:
How to handle security of temporary data on web server?
I'm primarily an ASP.NET developer but this question really applies regardless of language.  So obviously it is a good idea to prevent external attacks that arise from session hijacking and csrf attacks as well.  But what about internal attacks when the data involved is temporary, needed for the entire session but also sensitive and worth stealing?  There is the naturally just only hire trustworthy people route, but lets say that doesn't apply.

Say it is a given you already have code reviews and strict production data access permissions to prevent theft by developers.  The application encrypts sensitive data before storing to prevent theft by dbas.

How do you protect your temporary sensitive data against web server admins?  It seems that they could retrieve information by inspecting web server logs, traffic sniffing and inspection of process memory contents.  Naturally I would say production web server admins do not have access to the raw source code.

答:
If you cannot trust your own sysadmins with your servers, almost all is lost. The only way to protect sensitive data from somebody with root / administrator access to a production machine is to encrypt it against a key inaccessible to the sysadmin; for example, if the data is only ever used on the client, you could consider client-side encryption. But even then, there is nothing stopping a rogue sysadmin from just changing the server-side code that causes client-side encryption to, well, not encrypt anymore, or use a compromised encryption key. You gain little, but you sacrifice a lot of convenience and performance.

That doesn't mean you shouldn't consider temporary data from a security point of view: often, there are many users with nonprivileged access to a server; even if those can't log in directly (e.g. service accounts), an attacker who exploits other vulnerabilities may very well gain a shell with such a user. Naive use of memcache is easily exploited - you just need to connect to memcache locally, find the key you're interested in, and read the data. Tempfiles are slightly harder to get to, but certainly not impossible.

As with all things security: define your threats, find possible mitigations, and make a cost/benefit analysis.


答:
First, you need to understand what functions are used for. You might say, that a function provides a service: It does something for you.

Functions

Provide a service

don't know you exist

A printer for example is some kind of a service: It prints documents for you, you don't have to do it yourself. If you provide the printer with the necessary information (the parameters), the printer will happily do its job.

The printer does not know what data it will receive, otherwise, it wouldn't need a parameter. The parameter is the "unknown" that is needed to perform the service.

```<code>def my_function(a, b):
    pass
</code>```

This provides a service (or function) that wants two pieces of information from you. Once it has this information, it needs to be able to refer to it somehow. The notation (a, b) simply means that whatever you give it as first "information", will accessible from the name a and what you pass second will be accessible from the name b.

When you actually call the function (i.e. tell the printer to actually print something), you need to fill in these gaps of knowledge like so:

```<code>my_function(data_that_i_know, other_data_that_i_know)
</code>```

Your questions

How does the function buildConnectionString with the argument (params) know to get it's data from the variable myParams?

It doesn't. Does my printer know I am going to print a document relating to programming tomorrow? No. Tomorrow, I will send the information to my printer, which it will then happily print. The printer does not even know I exist.

Similarly, you "send" (pass) the data (myParams) to your function with the following expression:

```<code>buildConnectionString(myParams)
</code>```

At some other point in your program, you may wish to execute your function with different data. Similar to the printer, the function doesn't know who will call it, or when it will be called, or with what data it will be called.

Or params.items(), too within the return line?

The function, once executed, has received some data so it can do its job. This will execute a function called items() on whatever has been given the function to work with.

An example function

I want to create my own service, that can calculate the square of a number. This implies, that it needs to be given a number in order to work. After all, you can't square nothing, can you?

The function does not know, which number it will be given. However, in order to be able to multiply this number, we need to be able to refer to it somehow, hence, we give it a name: x.

```<code>def square(x):
    return x * x
</code>```

This defines a function called square that needs to be given one piece of data (the x).

I can now use this function to square a number:

```<code>>>> print square(2) # "Please square this number 2 for me"
4
</code>```

Within the function, x now refers to the value 2.

But I could also have called the function with the number 3:

```<code>>>> print square(3) # "Please square this number 2 for me"
9
</code>```

I could have chosen the name two instead of x for my function. But that would be misleading: The value does not have to be 2, it can be whatever I wish it to be.

And is there a reason behind not naming your variable params, or vice
  versa naming your argument in your function myParams?

Names in programming can be chosen arbitrarily, as long as they are not reserved by the language (these are called keywords).

Usually, you will name your variables whatever makes sense in that context. For instance, in code about geometric objects, my local variable may be named area which I will then square using the square() function. In code about a car I may have a variable named weight on the otherhand. I am sure you will agree that I being able to call square with square(weight) and square(area) conveys a lot of information.

Would you now change the parameter of square from x to weight_or_area? I hope you wouldn't. What if I was to use the function in connection with lengths? You will have to get used to the fact that parameters and arguments of functions are usually named differently, that is a Good Thing®.

It's just been
  extremely confusing seeing the argument set as one word, and then
  having the variable named something completely different, but having
  the function still be able to read your code, even when the argument
  name is different from your variable with the data you're printing
  from.

It is important to understand, that the function does not read your code. It has no idea it even exists. This brings us back to the printer analogy: Does it know you or I exist? Not, it's there to perform a job, no questions asked. The same thing applies to functions: They are there to do our bidding. They do not act on their own and "read code" to see where they are referenced.

Title: Confusion regarding def function within Python

Body:
I've been learning Python for about 2 months now (Started with Learn Python The Hard Way, now reading Dive Into Python), and within both books, I still seem to be confused over this one bit of code.

Lets just take the default code that Dive Into Python uses as an example:

```<code>def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim",
                "database":"master",
                "uid":"sa",
                "pwd":"secret"
               }

print buildConnectionString(myParams)
</code>```

How does the function buildConnectionString with the argument (params) know to get its data from the variable myParams?  Or params.items(), too within the return line?  Wouldn't the argument in buildConnectionString need to be set as buildConnectionString(myParams) in order for it to read properly?  How can you set the variable of your data to myParams, but have the argument of your function be params and have it read?  How does it know to read myParams as params?

And is there a reason behind not naming your variable params, or vice versa naming your argument in your function myParams?  It's just been extremely confusing seeing the argument set as one word, and then having the variable named something completely different, but having the function still be able to read your code, even when the argument name is different from your variable with the data you're printing from.

Body:
First, you need to understand what functions are used for. You might say, that a function provides a service: It does something for you.

Functions

Provide a service

don't know you exist

A printer for example is some kind of a service: It prints documents for you, you don't have to do it yourself. If you provide the printer with the necessary information (the parameters), the printer will happily do its job.

The printer does not know what data it will receive, otherwise, it wouldn't need a parameter. The parameter is the "unknown" that is needed to perform the service.

def my_function(a, b):
    pass

This provides a service (or function) that wants two pieces of information from you. Once it has this information, it needs to be able to refer to it somehow. The notation (a, b) simply means that whatever you give it as first "information", will accessible from the name a and what you pass second will be accessible from the name b.

When you actually call the function (i.e. tell the printer to actually print something), you need to fill in these gaps of knowledge like so:

my_function(data_that_i_know, other_data_that_i_know)

Your questions

How does the function buildConnectionString with the argument (params) know to get it's data from the variable myParams?

It doesn't. Does my printer know I am going to print a document relating to programming tomorrow? No. Tomorrow, I will send the information to my printer, which it will then happily print. The printer does not even know I exist.

Similarly, you "send" (pass) the data (myParams) to your function with the following expression:

buildConnectionString(myParams)

At some other point in your program, you may wish to execute your function with different data. Similar to the printer, the function doesn't know who will call it, or when it will be called, or with what data it will be called.

Or params.items(), too within the return line?

The function, once executed, has received some data so it can do its job. This will execute a function called items() on whatever has been given the function to work with.

An example function

I want to create my own service, that can calculate the square of a number. This implies, that it needs to be given a number in order to work. After all, you can't square nothing, can you?

The function does not know, which number it will be given. However, in order to be able to multiply this number, we need to be able to refer to it somehow, hence, we give it a name: x.

def square(x):
    return x * x

This defines a function called square that needs to be given one piece of data (the x).

I can now use this function to square a number:

>>> print square(2) # "Please square this number 2 for me"
4

Within the function, x now refers to the value 2.

But I could also have called the function with the number 3:

>>> print square(3) # "Please square this number 2 for me"
9

I could have chosen the name two instead of x for my function. But that would be misleading: The value does not have to be 2, it can be whatever I wish it to be.

And is there a reason behind not naming your variable params, or vice
  versa naming your argument in your function myParams?

Names in programming can be chosen arbitrarily, as long as they are not reserved by the language (these are called keywords).

Usually, you will name your variables whatever makes sense in that context. For instance, in code about geometric objects, my local variable may be named area which I will then square using the square() function. In code about a car I may have a variable named weight on the otherhand. I am sure you will agree that I being able to call square with square(weight) and square(area) conveys a lot of information.

Would you now change the parameter of square from x to weight_or_area? I hope you wouldn't. What if I was to use the function in connection with lengths? You will have to get used to the fact that parameters and arguments of functions are usually named differently, that is a Good Thing®.

It's just been
  extremely confusing seeing the argument set as one word, and then
  having the variable named something completely different, but having
  the function still be able to read your code, even when the argument
  name is different from your variable with the data you're printing
  from.

It is important to understand, that the function does not read your code. It has no idea it even exists. This brings us back to the printer analogy: Does it know you or I exist? Not, it's there to perform a job, no questions asked. The same thing applies to functions: They are there to do our bidding. They do not act on their own and "read code" to see where they are referenced.


答:
It depends on the programming language. A language with strict static typing and a compilation step in the build process will catch most typos; the stricter the language, the higher the chance of a typo causing invalid syntax. An extreme example is the Haskell programming language - Haskell programmers often claim, half-jokingly, that once a Haskell program compiles, it is usually correct and bug-free. There are still typos that slip through the net though; a famous example is = vs. == in C/C++. Coding style can provide some extra protection; static code analysis may detect suspicious code; a text editor with auto-completion lowers the chance of typos; but ultimately, there is no substitute for actual testing.

If you use a dynamic language, things are more dire - typically, there is no compilation step, so all errors surface as runtime errors, none of them prevent deployment by nature. Worse yet, many errors will only be noticed once the offending code gets executed. This makes (automated) testing even more vital than with strict static compiled languages.

But then, automated tests have their own problem: coverage. For automated tests to catch all errors, you need 100% code coverage (that is, your tests must touch every single line of code), but you also need 100% input coverage (your tests must call each unit with every possible set of inputs, in every possible state of the context). 100% code coverage is doable, but 100% input coverage is hard to impossible for everything non-trivial. Your best bet is to make educated guesses about sets of inputs that might hit edge cases and hope you don't miss any. And since tests are (out of necessity) written by humans, you can make mistakes while writing tests just like you can mistakes while writing the code to be tested. Luckily, more often than not, a bug in the test does not cancel out a bug in the tested code but rather causes the test to fail doubly.

Here's what you can do to prevent and mitigate typos:

Be religious about unit-testing everything.

Set up your development environment to run all the tests for you automatically: if you have a continuous-integration system in place, configure it to run all unit tests on each build, and consider any build broken if any test fails. Otherwise, consider using source control hooks or similar features to run tests before pushing your changes upstream.

Code defensively, avoid 'clever' tricks, use dynamic features conservatively.

If your programming language has options to be more strict (e.g. Option Strict and Option Explicit in VisualBasic), turn them on.

If your programming language can warn about suspicious code, make it so (not on production systems though), and treat every warning as a fatal error.

Make good use of safeguards built into the language (e.g. PHP's type hinting).

Use a code editor that provides auto-completion; use it.

When naming identifiers, avoid 'near-misses': don't use $User and $user within the same context.

Keep your scope as local and small as possible: avoid global state, expose only what you have to, avoid side effects, etc. This avoids accidentally touching things in completely unrelated places, and makes your code easier to test.

Have someone else review your code.

None of these are bullet-proof, but combining them covers most of your bases and reduces the risk to, hopefully, acceptable levels.

Title: How to avoid typo errors, etc?


问:
Pros and cons of intrusive and non-intrusive serialization?
I am interesting in the pros and cons of serialization: intrusive and non-intrusive.

On the one hand it seems non-intrusive is easy to use - class to be serialized should not be updated. It seems convenient for simple cases. E.g. XStream.Net implements such approach.

But the issues can appear if this class is connected in some way with other classes, e.g. stores indices of global objects which should be serialized as well. In this case non-intrusive approach looks dangerous.

Concerning intrusive implementation. It is good that developer can directly specify what and how to serialize (of course if serialization technology is flexible enough).

E.g. Microsoft .Net has intrusive approach implemented for XML serialization - attributes should be specified for classes and members.

Other ideas?

答:
From C++ perspective there is a very informative article, which every developer needs to read at once. It basically lays down the difference in serialization for approached intrusive  and non-intrusive.

A practical guide to C++ serialization is another well written source to be aware of. More info from Boost C++ libraries on Serializable Concept.


问:
why is a naturally ordered set generated at 9 but not 10 digits
code found at: https://softwareengineering.stackexchange.com/q/158606/44933

Presuming that the problem indicated above is due to the test app and not due specifically to method generateRandomDigits().

When NUMBER_OF_DIGITS_TO_ORDER is <= 9, I do get a naturally ordered sets (just trying to prove that it is possible), but when it is set to 10 I never get such a set and I've run it many times. Why?

I am more than open to suggested improvements to method generateRandomDigits() - it seems a bit convoluted.

答:
You need to try harder - in the sense, more attempts are needed to increase chances to get 10 digits set.

Regarding the program, it would greatly benefit from logging improvement. The way it is done now, program output just lacks an information that would help to identify what is going on there.

If you add few lines to the main method to count the number of found arrays and re-run the program with improved logging, you will likely get a much better feeling of where it all is coming at as the value NUMBER_OF_DIGITS_TO_ORDER increases. Consider logging like this:

```<code>public static void main(String[] args1) {
    loadNaturalOrderedArray();
    // let's count our attempts
    long numberOfChecks = 0;
    // let's count our luck
    long numberOfNaturalOrdered = 0;
    for (int i = 0; i < TRIALS; i++) {
        ArrayList<char[]> listOfArrays = new ArrayList<char[]>(NUMBER_OF_CHAR_ARRAYS);
        for (int j = 0; j < NUMBER_OF_CHAR_ARRAYS; j++) {
            listOfArrays.add(j, generateRandomDigits());
        }
        for (int j = 0; j < NUMBER_OF_CHAR_ARRAYS; j++) {
            numberOfChecks++; // count our attempts
            char[] current = listOfArrays.get(j);
            if (isNaturalOrdered(current)) {
                numberOfNaturalOrdered++; // count our luck
                //printNaturalOrdered(current); // not important
            }
        }
        System.out.println("trial " + i + " is done");
        System.out.println("--------------------------------\n");
    }
    // print our luck
    System.out.println("number of natural ordered: [" + numberOfNaturalOrdered + "]");
    // print our attempts
    System.out.println("number of checks: [" + numberOfChecks + "]");
    // btw numberOfChecks is always TRIALS * NUMBER_OF_CHAR_ARRAYS
    System.out.println("DONE");
}
</code>```

Let's start with "small" case to see how things go. Look, program drops random (unique) digits, say from 0 to 2 into 3628800 arrays (NUMBER_OF_CHAR_ARRAYS) - making essentially 3628800 attempts and checking how much times it gets get 0,1,2. We sure get it a lot.

Thing is, there are only 3*2=6 possible combinations that could get into our randomly generated array - first place can be occupied by any of three digits, second place can be occupied by any of two remaining digits; as for the third place, we don't have any options here as long as first and second places are occupied. Given this, we can expect to get about 3628800/6=600000.

Okay, now let's do the same to digits 0 to 6. Number of attempts remains the same, 3628800, but array we want is getting harder to randomly generate because it's longer: 0,1,2,3,4,5,6. For array of this length, there are 6*5*4*3*2 possible combinations - and our chances to get it with same 3628800 are 6*5*4=120, more than hundred times lower than were with array 0,1,2. And it only will get worse as the length of array increases.

Finally, let's try "win a lottery", to get 0,1,2,3,4,5,6,7,8,9 - all the ten digits perfectly lined up - with the same number of attempts that brought us so much luck with 3 digits, noticeably less luck with 6 digits and pretty shaky luck with 9 digits? "Pretty shaky" - in my trial runs, I was getting nine digits 2 to 5 times; getting yet another digit "in the line" is likely to be 10 times harder than that.

There are whopping 10*9*8*7*6*5*4*3*2 combinations possible with 10 unique digits - this makes our chances 10*9*8*7~=5000, about five thousand times worse that what we've got for our number of attempts for 6-digit ordered set.

Expecting 10 digits ordered set to show is pretty much like buying hundred lottery tickets and wondering

why didn't I win jackpot?

Body:
You need to try harder - in the sense, more attempts are needed to increase chances to get 10 digits set.

Regarding the program, it would greatly benefit from logging improvement. The way it is done now, program output just lacks an information that would help to identify what is going on there.

If you add few lines to the main method to count the number of found arrays and re-run the program with improved logging, you will likely get a much better feeling of where it all is coming at as the value NUMBER_OF_DIGITS_TO_ORDER increases. Consider logging like this:

public static void main(String[] args1) {
    loadNaturalOrderedArray();
    // let's count our attempts
    long numberOfChecks = 0;
    // let's count our luck
    long numberOfNaturalOrdered = 0;
    for (int i = 0; i < TRIALS; i++) {
        ArrayList<char[]> listOfArrays = new ArrayList<char[]>(NUMBER_OF_CHAR_ARRAYS);
        for (int j = 0; j < NUMBER_OF_CHAR_ARRAYS; j++) {
            listOfArrays.add(j, generateRandomDigits());
        }
        for (int j = 0; j < NUMBER_OF_CHAR_ARRAYS; j++) {
            numberOfChecks++; // count our attempts
            char[] current = listOfArrays.get(j);
            if (isNaturalOrdered(current)) {
                numberOfNaturalOrdered++; // count our luck
                //printNaturalOrdered(current); // not important
            }
        }
        System.out.println("trial " + i + " is done");
        System.out.println("--------------------------------\n");
    }
    // print our luck
    System.out.println("number of natural ordered: [" + numberOfNaturalOrdered + "]");
    // print our attempts
    System.out.println("number of checks: [" + numberOfChecks + "]");
    // btw numberOfChecks is always TRIALS * NUMBER_OF_CHAR_ARRAYS
    System.out.println("DONE");
}

Let's start with "small" case to see how things go. Look, program drops random (unique) digits, say from 0 to 2 into 3628800 arrays (NUMBER_OF_CHAR_ARRAYS) - making essentially 3628800 attempts and checking how much times it gets get 0,1,2. We sure get it a lot.

Thing is, there are only 3*2=6 possible combinations that could get into our randomly generated array - first place can be occupied by any of three digits, second place can be occupied by any of two remaining digits; as for the third place, we don't have any options here as long as first and second places are occupied. Given this, we can expect to get about 3628800/6=600000.

Okay, now let's do the same to digits 0 to 6. Number of attempts remains the same, 3628800, but array we want is getting harder to randomly generate because it's longer: 0,1,2,3,4,5,6. For array of this length, there are 6*5*4*3*2 possible combinations - and our chances to get it with same 3628800 are 6*5*4=120, more than hundred times lower than were with array 0,1,2. And it only will get worse as the length of array increases.

Finally, let's try "win a lottery", to get 0,1,2,3,4,5,6,7,8,9 - all the ten digits perfectly lined up - with the same number of attempts that brought us so much luck with 3 digits, noticeably less luck with 6 digits and pretty shaky luck with 9 digits? "Pretty shaky" - in my trial runs, I was getting nine digits 2 to 5 times; getting yet another digit "in the line" is likely to be 10 times harder than that.

There are whopping 10*9*8*7*6*5*4*3*2 combinations possible with 10 unique digits - this makes our chances 10*9*8*7~=5000, about five thousand times worse that what we've got for our number of attempts for 6-digit ordered set.

Expecting 10 digits ordered set to show is pretty much like buying hundred lottery tickets and wondering

why didn't I win jackpot?


问:
Is my mediator layer a sensible way to manage this scenario using the Single Responsibility Principle?
I'm not sure how to start to explain my question, but here goes.

We have just finished an MVC application that hits 2 WCF services. But there has been a bit of a disagreement between those who worked on the project and some who haven't over the design used. What we have is two WCF services, one on each site (site specific data) and another at head office (data shared/common between all sites). Normally we would have two apps, one for site and another for head office. In this case I decided from a UX point of view that it would be better to have it look like one app from the users point of view so they would not need know two urls. Basically, the user does not know if they are hitting site or head office.

Now comes the design decision that has caused the disagreements.
The MVC App has controllers that need to hit either a site wcf service or a head office WCF service. So to prevent the need of the controllers needing to be aware of the two WCF communications layers and converting the WCF results into a model the controllers could use, I created a layer in between the controllers and WCF Proxies. Which accepts a request from a controller, then calls the appropriate site or central WCF proxy call, then if needed, convert the WCF result into a model that the controller can use.

This layer, I called a Mediator, but after much discussion, I am of the opinion that it is not the correct description for it. Anyway, the reason for this layer is when tring to keep to the SOILD object oriented principles, in particular the Single Responsibility Principal. The controllers responsibility is to handle client requests and return a view/result. It should not need to know or maintain a WCF proxy and convert its result. (It could go directly to a database instead of a WCF call but the controller shouldn't be responsible or even aware of that because it is responsible for the view) The same goes for the WCF proxy, it should not know what is consuming its result and that the WCF data contract should be converted into a model specific for each controller. The mediator layer in between is what decides which WCF service and method to call and then either via a extension method or a specific handler converts the result to a model the controller can use. (sometimes it may take several wcf calls to create the model).

```<code>Controller1 -> Mediator -> HeadOfficeWCFProxy
Controller2 -> Mediator -> SiteWCFProxy
</code>```

So the controller asks for data (not knowing where it comes from)

The mediator converts and passes the request to the appropriate WCF Proxy(s)

The WCF Proxy(s) make the calls across the wire and return the results.

The mediator then converts the result(s) into a model (if needed) via an extension method and returns it to the controller.

The controller renders the view using said model.

Now what I described here was just on the MVC side. I have a similar setup on the WCF service side but the mediators benefit is clearer.

On the head office WCF service

```<code>WCFListener -> Mediator -> DataLayer (LinqToSQL)
                        -> SiteSyncHandler (sends change to all sites asyncronously)
                        -> ThirdPartyContentManagementHandler (via web service)
</code>```

Now the devs that have worked on the project, like the separation of concerns alot as it is very clear where everything belongs and keeps code to a minimum in each layer. But the down side in the MVC app is for a lot of the calls the mediator just makes a single WCF call and doesn't even need to convert the result (most of the time the data contract is fine for use as a model) resulting in a fair amount of one liner method boiler plate code. The mediator doesn't really add much in that scenario except to keep things consistent across controllers. Some devs that haven't worked on the project, insist that there is no need at all for the Mediator layer and that it could be all handled by the controllers themselves. Which means maintaining the appropriate WCF Proxy in each controller. This in my mind violates the Single Responsibility principle. To which they argue that SOLID is more like a set of guidelines, and not to be blindly followed. Which while I kinda agree with that statement its also not to be blindly ignored.

I have conceded that the term mediator is not really appropriate (perhaps director or relay), but I still think the basic design is valid, and would use it again. The same can be said for those who have worked on the project. I would like to know what other people think. Is there a better solution or have I "over complicated it". (I still don't agree that is is complicated, its a very simple concept and easy to maintain)

答:
I favor your side of the argument:

The controllers responsibility is to handle client requests and return a view/result. It should not need to know or maintain a WCF proxy and convert its result. (It could go directly to a database instead of a WCF call but the controller shouldn't be responsible or even aware of that because it is responsible for the view)

When using the MVC pattern, you must keep your controllers skinny.

Furthermore, if you put the client proxies directly in the controller, you lose your ability to use dependency injection and perform automated unit-testing.


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答:
I start with the tests.  If the unit tests and integration tests are well written, they describe the use cases.  If they are not well written, or not written at all (sadly, this is largely the case), I start with entry points in the code and match those with the design.

I'll then write tests for each use case, discovered by the tree you'll find after investigating entry points, to probe the code and use code coverage utilities to see what I'm missing.  These tests tell me exactly how the code works.

I always try to add value to something I look at; writing tests, cleaning up code, refactoring large (20+ lines) functions.

I find that creating documentation alone does not add any real value to the code since it never interacts with the code.


问:
High-level language to assembly
If assembly language is only a readable way to represent machine code, then why are HLLs converted to assembly first and then to machine code?

Shouldn't HLLs be directly converted to machine code?

答:
This is customary practice on Unix systems because it simplifies the compilers.  Compiling is largely not dependent on the gritty details of machine code, and many compilers can all target the same assembler.

Some compilers target an intermediate abstract machine (like JVM) or even an intermediate concrete machine (MIPS) which is not the actual hardware the code will everntually run on.

Some compilers do go directly to machine code.  It's not very portable and portability is a big thing now (it didn't used to be back in the stone age of computing.)

Title: High-level language to assembly


问:
What is the benefit of using getters and setters on properties in C#?

Possible Duplicate:

  When are Getters and Setters Justified

Why do we use get and set method in C#? And why do we use public and private method property?

For example:

```<code>public class Date
{
    private int month = 7;
    public int Month
    {
        get
        {
            return month;
        }
        set
        {
            if ((value > 0) && (value < 13))
            {
                month = value;
            }
        }
    }
}
</code>```

答:
Private set modifier is used to control the access to object's property value.

Public set modifier is directly accessing the object's property value.

When you have a closed Domain, as a rule of open/close principle, private set modifiers used to restrict direct access to modify the properties of the object.

Private setters were not available before .NET 2.0 Framework. This has meant that people have written separate SetXXX methods if they wanted a public getter but a more limited setter.

```<code>public class MyTest
{
    string someProperty;

    public string SomeProperty
    {
        get
        {
            return someProperty;
        }

        private set
        {
            someProperty = value;
        }
    }
}
</code>```

The basic rules are that you can't specify an access modifier for both the getter and the setter, and you have to use the "extra" modifier to make access more restrictive than the rest of the property.

Your question example comes from MSDN article Using Properties (C# Programming Guide).
Look at that again and it will clear up the things.

Body:
Private set modifier is used to control the access to object's property value.

Public set modifier is directly accessing the object's property value.

When you have a closed Domain, as a rule of open/close principle, private set modifiers used to restrict direct access to modify the properties of the object.

Private setters were not available before .NET 2.0 Framework. This has meant that people have written separate SetXXX methods if they wanted a public getter but a more limited setter.

public class MyTest
{
    string someProperty;

    public string SomeProperty
    {
        get
        {
            return someProperty;
        }

        private set
        {
            someProperty = value;
        }
    }
}

The basic rules are that you can't specify an access modifier for both the getter and the setter, and you have to use the "extra" modifier to make access more restrictive than the rest of the property.

Your question example comes from MSDN article Using Properties (C# Programming Guide).
Look at that again and it will clear up the things.


问:
Dynamic choice of compilers?
An application has the following logic:

client => created *.cpp => sent to the server => cl.exe + *.cpp =

*.exe

client => created *.cs => sent to the server => csc.exe + *.cs =

*.exe

client => created *.pas => sent to the server => PascalCompiler +

*.pas = *.exe

etc.

The language - C#. I hear that MSBUILD can help me, but I don't understand how to change compiler on server at runtime. Does anyone know of options other than Process class?

I'm trying to write an online system to test programs in programming contests. The programmer selects the compiler and sends the source code to the server for verification.

And I do not need to build the project, I just need to compile a single file.

答:
It sounds like you are trying to automate a build process? A few more details of what you want to achieve would help.

MsBuild is Microsoft's build tool, not sure if it will help you with Pascal. Other tools that will include NAnt.

Have a look at Continuous integration, and CC.Net (CruiseControl.Net) There are other tools as well.

I'm sort of guessing what you want a bit, so please add a few more details.

Title: Dynamic choice of compilers?


问:
Are the terms stable and reliable interchangeable?
Is there a difference between stability and reliability (at least in software engineering context) or can they be used interchangeably? If not, what would be some examples of reliable but not necessarily stable systems, and vice versa?

答:
To my mind, "reliability" means you have a grasp on the bound of the system. You can, with confidence, say that "we provide response time X at the Xth percentile" (the higher the X, the better, obviously).

Stability, on the other hand, is merely an availability measure. "If you try to connect tio our service, it will be there at least X% of the times".


问:
How to ease the maintenance of event driven code?
When using an event based component I often feel some pain at maintenance phase.

Since the executed code is all split around it can be quite hard to figure what will be all the code part that will be involved at runtime.

This can lead to subtle and hard to debug problems when someone adds some new event handlers.

Edit from comments:
Even with some good practices on-board, like having an application wide event bus and handlers delegating business to other part of the app, there is a moment when the code starts to become hard to read because there is a lot of registered handlers from many different places (especially true when there is a bus).

Then sequence diagram starts to look over complex, time spend to figure out what is happening is increasing and debugging session becomes messy (breakpoint on the handlers manager while iterating on handlers, especially joyful with async handler and some filtering on top of it).

//////////////

Example

I have a service that is retrieving some data on the server. On the client we have a basic component that is calling this service using a callback. To provide extension point to the users of the component and to avoid coupling between different components, we are firing some events: one before the query is sent, one when the answer is coming back and another one in case of a failure.
We have a basic set of handlers that are pre-registered which provide the default behavior of the component.

Now users of the component (and we are user of the component too) can add some handlers to perform some change on the behavior (modify the query, logs, data analysis, data filtering, data massaging, UI fancy animation, chain multiple sequential queries, whatever).
So some handlers must be executed before/after some others and they are registered from a lots of different entry point in the application.

After a while, it can happens that a dozen or more handlers are registered, and working with that can be tedious and hazardous.

This design emerged because using inheritance was starting to be a complete mess. The event system is used at a kind of composition where you don't know yet what will be your composites.

End of example

//////////////

So I'm wondering how other people are tackling this kind of code. Both when writing and reading it.

Do you have any methods or tools that let you write and maintain such code without to much pain ?

答:
I've found that processing events using a stack of internal events (more specifically, a LIFO queue with arbitrary removal) greatly simplifies event-driven programming. It allows you to split the processing of an "external event" into several smaller "internal events", with well-defined state in between. For more information, see my answer to this question.

Here I present a simple example which is solved by this pattern.

Suppose you are using object A to perform some service, and you give it a callback to inform you when it's done. However, A is such that after calling your callback, it may need to do some more work. A hazard arises when, within that callback, you decide that you don't need A any more, and you destroy it some way or another. But you're being called from A - if A, after your callback returns, cannot safely figure out that it was destroyed, a crash could result when it attempts to perform the remaining work.

NOTE: It's true that you could do the "destruction" in some other way, like decrementing a refcount, but that just leads to intermediate states, and extra code and bugs from handling these; better for A to just stop working entirely after you don't need it anymore other than continue in some intermediate state.

In my pattern, A would simply schedule the further work it needs to do by pushing an internal event (job) into the event loop's LIFO queue, then proceed to call the callback, and return to event loop immediately. This piece of code it no longer a hazard, since A just returns. Now, if the callback doesn't destroy A, the pushed job will eventually be executed by the event loop to do its extra work (after the callback is done, and all its pushed jobs, recursively). On the other hand, if the callback does destroy A, A's destructor or deinit function can remove the pushed job from the event stack, implicitly preventing execution of the pushed job.