答:
Pipe & Filter is what you're looking for.

http://msdn.microsoft.com/en-us/library/dn568100.aspx

Basically, you define a standard input object and a standard output object. In object oriented programmation, you can easily define those as interfaces. The filters take the standard input object, apply some transformations and returns a standard output object. Because every filters takes the same input and output, you can chain them together however you like. You can easily produce parallel pipes to take advantage of multithreaded processors.

You could also create a configuration object to define flows of operations; your solution would then be reusable.

Title: Is there a design pattern for dynamically applying transformations or filters to a model?

Body:
For example, there is a model of an event with certain attributes that can be adjusted by existing processes: maybe one that looks at a geo-location stamp and determines a nearby city; another that looks at the number of registrations and applies rounding; another that calculates local popularity based on attendees vs. nearby events.

The important piece is having a way to dynamically order the operations--the filters/transformations/processing tasks--so that you can pass the events to a processing object that arranges the tasks in the correct order for the configuration/situation, and then passes the models through to apply them.

I can think of some ugly ways to make this happen, but want to know if there is a SOLID pattern that would allow for better, more-testable code.


问:
Can all the recursive functions be coded with iterations?
What are the advantages of recursion?

Some programming languages can optimize tail recursion, but, still in general terms, recursion consume more resources than regular loops.

Is it possible to have an iterative version of some recursive function?

答:
I believe that recursion is one of those tools that a programmer must have to live. With recursion you can "think" your algorithms and solve them just the way you thought about it. But, I must warn you, everybody is talking about how pretty recursion is and how much simplicity brings to the code, regarding that I have a few things to say:

First of all, thinking the "recursive way" of an algorithm is not easy. Building a function like a factorial(n!) or something like Hanoi Towers is just the tip of the iceberg, and reaching the bottom requires a looong time.

Don't think that recursion brings simplicity only into your code, sometimes, the iterative way is ugly and messy, but is cost effective (look into the recursive solution of the Fibonacci problem)

Having those things in mind, learn recursion! it's funny, complex and it will smash your brain!, but you'll find yourself loving it.

Best of luck!

ContentLicense: CC BY-SA 2.5


问:
Is it safe to convert Windows file paths to Unix file paths with a simple replace?
So for example say I had it so that all of my files will be transferred from a windows machine to a unix machine as such: C:\test\myFile.txt to {somewhere}/test/myFile.txt (drive letter is irrelevant at this point).

Currently, our utility library that we wrote ourselves provides a method that does a simple replace of all back slashes with forward slashes:

```<code>public String normalizePath(String path) {
   return path.replaceAll("\\", "/");
}
</code>```

Slashes are reserved and cannot be part of a file name, so the directory structure should be preserved. However, I'm not sure if there are other complications between windows and unix paths that I may need to worry about (eg: non-ascii names, etc)

答:
Yes, if you only do the replacement on Windows, and turn it off when running on other systems.

Doing the replacement on Unix-like systems is wrong because \ is a valid character in a file or directory name on Unix-like platforms. On these platforms, only NUL and / are forbidden in file and directory names.

Also, some Windows API functions (mostly the lower level ones) do not allow the use of forward slashes ― backslashes must be used with them.

Edit: It turns out that there are some special file systems on Windows on which / and NUL are valid characters, such as the Registry (available at \\?\GLOBALROOT\Registry from a Windows API perspective, or \Registry from the Native API perspective).  In the Named Pipe File System (usually mounted at \??\pipe), all characters (including /, \, and even NUL) are valid.  So in general, not only is it not valid to replace / with \ on Windows, it is not valid to assume that every Windows file can be accessed using the Windows API!  To reliably access arbitrary files, one must use the Native API (NtCreateFile and friends).  NtCreateFile also exposes an equivalent of openat(2), which isn’t exposed via the Windows API.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Omitting "destructors" in C is taking YAGNI too far?
I'm working on a medium embedded application in C using OO-like techniques. My "classes" are .h/.c modules using data structs and function pointers structs to emulate encapsulation, polymorphism, and dependency injection.

Now, one would expect a myModule_create(void) function to come with a myModule_destroy(pointer) counterpart. But the project being embedded, the resources that are instantiated realistically should never be released.

I mean, if I have 4 UART serial ports and I create 4 UART instances with their required pins and settings, there's absolutely no reason to ever want to destroy UART #2 at some point during runtime.

So following the YAGNI (You ain't gonna need it) principle, should I omit the destructors? This seem extremely strange to me but I can't think of a use for them; resources are freed when the device powers-off.

答:
If you don't provide a way to dispose the object, you are passing a clear message that they have "infinite" lifetime once created. If this makes sense to your application, I say: do it.

Glampert is right; there is no need for destructors here. They would just create code bloat and a pitfall for users (using an object after its destructor is called is undefined behavior).

However, you should be sure that there is really no need to dispose of the objects. For instance, do you need to have an object for a UART that is not currently in use?


问:
Is using MultiMaps code smell? If so what alternative data structures fit my needs?
I'm trying to model nWoD characters for a roleplaying game in a character builder program. The crux is I want to support saving too and loading from yaml documents.

One aspect of the character's is their set of skills. Skills are split between exactly three 'types': Mental, Physical, and Social. Each type has a list of skills under if. My Yaml looks like this:

```<code>PHYSICAL:
    Athletics: 0
    Brawl: 3
MENTAL:
    Academics: 2
    Computers
</code>```

My initial thought was to use a Multimap of some sort, and have the skill type as an Enum, and key to my map. Each Skill is an element in the collection that backs the multimap.

However, I've been struggling to get the yaml to work. On explaining this to a colleague outside of work they said this was probably a sign of code smell, and he's never seen it used 'well'.

Are multiMaps really code smell? If so what alternate data structures would suit my goals?

答:
A couple of notes:

    Never deserialize untrusted YAML. In most YAML parsers this allows arbitrary code execution. In SnakeYAML, you can prevent this, but you need to be very careful, and the risk seems unnecessary.

Since you just need a key-value store I would recommend JSON instead, which brings me to:

    Use strings as keys, and convert from strings to enums after loading (You can do this with a switch statement or by reflection.). This avoids the need for calling Java constructors from the YAML parser, and thus eliminates the security vulnerability. The conversion can easily be made where needed, and hopefully will not cause much of a slowdown.


问:
Should I use the repository in the Domain Object or push the Domain Object back to the Service Layer?
I have come from a transaction script world and I am just starting to take a look at DDD. I am unsure of the correct way to integrate a DDD design with database persistence. This is what I have:

A service class called OrganisationService whose interface contains methods for retrieving and saving away instances of Organisation domain objects. Organisation is an aggregate root and has other data related to it: Members and Licenses. EF6 database first DBContext is used within the OrganisationService to retrieve OrganisationDB entities and the related MemberDB and LicenseDB entities. These all get transformed into their domain object class equivalents when retrieved by the OrganisationService and loaded into the Organisation domain object. This object looks like so:

```<code>public class Organisation
{
    public IList<Member> Members { get; set; }
    public IList<License> Licenses { get; set; }
}
</code>```

I am not using the Repository pattern in the OrganisationService...I am using EF itself as the Repository as it seems that EF6 has largely made repository redundant now.

At this point in the design the Organisation domain object is anaemic: it looks like the EF POCO Organisation class. The OrganisationService class looks a lot like a Repository!

Now I need to start adding logic. This logic includes managing an Organisations Licenses and Members. Now in the transaction script days I would add methods into the OrganisationService for handling these operations and call into a Repository to interact with the DB, but with DDD I believe this logic should be encapsulated within the Organisation domain object itself...

This is where I am unsure of what I should be doing: I will need to persist this data back to the database as part of the logic. Does this mean I should use DbContext within the Organisation domain object to do this? Is using the repository/EF within the domain object bad practice? If so, where does this persistence belong?

```<code>public class Organisation
{
    public IList<Member> Members { get; set; }
    public IList<License> Licenses { get; set; }

    public void AddLicensesToOrganisation(IList<License> licensesToAdd)
    {
        // Do validation/other stuff/

        // And now Save to the DB???
        using(var context = new EFContext())
        {
            context.Licenses.Add(...
        }

        // Add to the Licenses collection in Memory
        Licenses.AddRange(licensesToAdd);
    }
}
</code>```

Should I instead just be mutating the Organisation domain object in memory and then pushing it back to the OrganisationService for persistence? Then I have to track what actually changed on the object (which is what EF does to its own POCOs! I am kind of coming to feel that EF isn't just a repository replacement, but also could be the domain layer!)

Any guidance here is appreciated.

答:
You can take either approach and have it work well - there are, of course, pros and cons.

Entity Framework is definitely intended to suffuse your domain entities. It does work well when your domain entities and data entities are the same classes. It's much nicer if you can rely on EF to keep track of the changes for you, and just call context.SaveChanges() when you're finished with your transactional work. It also means that your validation attributes don't have to be set twice, once on your domain models and once on your persisted entities - things like [Required] or [StringLength(x)] can be checked in your business logic, allowing you to catch invalid data states before you try to do a DB transaction and get an EntityValidationException. Finally, it's quick to code - you don't need to write a mapping layer or repository, but can instead work directly with the EF context. It's already a repository and a unit of work, so extra layers of abstraction don't accomplish anything.

A downside to combining your domain and persisted entities is that you end up with a bunch of [NotMapped] attributes scattered throughout your properties. Often, you will want domain-specific properties which are either get-only filters on persisted data, or are set later in your business logic and not persisted back into your database. Some times, you'll want to express your data in your domain models in a way that doesn't work very well with a database - for example, when using enums, Entity will map these to an int column - but perhaps you want to map them to a human-readable string, so you don't need to consult a lookup when examining the database. Then you end up with a string property which is mapped, an enum property which isn't (but gets the string and maps to the enum), and an API which exposes both! Similarly, if you want to combine complex types (tables) across contexts, you may wind up with a mapped OtherTableId and an unmapped ComplexType property, both of which are exposed as public on your class. This can be confusing for someone who isn't familiar with the project, and unnecessarily bloats your domain models.

The more complex my business logic/domain, the more restrictive or cumbersome I find combining my domain and persisted entities to be. For projects with short deadlines, or that don't express a complex business layer, I feel that using EF entities for both purposes is appropriate, and there's no need to abstract your domain away from your persistence. For projects which need maximum ease-of-extension, or that need to express very complicated logic, I think you're better off separating the two and dealing with the extra persistence complexity.

One trick to avoiding the trouble of manually tracking your entity changes is to store the corresponding persisted entity ID in your domain model. This can be filled automatically by your mapping layer. Then, when you need to persist a change back to EF, retrieve the relevant persistent entity before doing any mapping. Then when  you map the changes, EF will detect them automatically, and you can call context.SaveChanges() without having to track them by hand.

```<code>public class OrganisationService
{
    public void PersistLicenses(IList<DomainLicenses> licenses)
    {
        using (var context = new EFContext())
        {
            foreach (DomainLicense license in licenses)
            {
                var persistedLicense = context.Licenses.Find(pl => pl.Id == license.PersistedId);
                MappingService.Map(persistedLicense, license); //Right-left mapping
                context.Update(persistedLicense);
            }
            context.SaveChanges();
        }
    }
}
</code>```

Body:
You can take either approach and have it work well - there are, of course, pros and cons.

Entity Framework is definitely intended to suffuse your domain entities. It does work well when your domain entities and data entities are the same classes. It's much nicer if you can rely on EF to keep track of the changes for you, and just call context.SaveChanges() when you're finished with your transactional work. It also means that your validation attributes don't have to be set twice, once on your domain models and once on your persisted entities - things like [Required] or [StringLength(x)] can be checked in your business logic, allowing you to catch invalid data states before you try to do a DB transaction and get an EntityValidationException. Finally, it's quick to code - you don't need to write a mapping layer or repository, but can instead work directly with the EF context. It's already a repository and a unit of work, so extra layers of abstraction don't accomplish anything.

A downside to combining your domain and persisted entities is that you end up with a bunch of [NotMapped] attributes scattered throughout your properties. Often, you will want domain-specific properties which are either get-only filters on persisted data, or are set later in your business logic and not persisted back into your database. Some times, you'll want to express your data in your domain models in a way that doesn't work very well with a database - for example, when using enums, Entity will map these to an int column - but perhaps you want to map them to a human-readable string, so you don't need to consult a lookup when examining the database. Then you end up with a string property which is mapped, an enum property which isn't (but gets the string and maps to the enum), and an API which exposes both! Similarly, if you want to combine complex types (tables) across contexts, you may wind up with a mapped OtherTableId and an unmapped ComplexType property, both of which are exposed as public on your class. This can be confusing for someone who isn't familiar with the project, and unnecessarily bloats your domain models.

The more complex my business logic/domain, the more restrictive or cumbersome I find combining my domain and persisted entities to be. For projects with short deadlines, or that don't express a complex business layer, I feel that using EF entities for both purposes is appropriate, and there's no need to abstract your domain away from your persistence. For projects which need maximum ease-of-extension, or that need to express very complicated logic, I think you're better off separating the two and dealing with the extra persistence complexity.

One trick to avoiding the trouble of manually tracking your entity changes is to store the corresponding persisted entity ID in your domain model. This can be filled automatically by your mapping layer. Then, when you need to persist a change back to EF, retrieve the relevant persistent entity before doing any mapping. Then when  you map the changes, EF will detect them automatically, and you can call context.SaveChanges() without having to track them by hand.

public class OrganisationService
{
    public void PersistLicenses(IList<DomainLicenses> licenses)
    {
        using (var context = new EFContext())
        {
            foreach (DomainLicense license in licenses)
            {
                var persistedLicense = context.Licenses.Find(pl => pl.Id == license.PersistedId);
                MappingService.Map(persistedLicense, license); //Right-left mapping
                context.Update(persistedLicense);
            }
            context.SaveChanges();
        }
    }
}


问:
Why to declare a String (as final) and then use it?
In a typical spring mvc validator class, while inserting an errorCode value in the Errors object, what difference does it make between using a String (props.somefield.req) like so

```<code>errors.rejectValue("elementId", "props.somefield.req");
</code>```

verses a declared static final String ?

```<code>private static final String SOMFIELD_REQ = "props.somefield.req"; ...
errors.rejectValue("elementId", SOMFIELD_REQ);
</code>```

Does it improve the performance even in a slightest way? I have read a few questions on stack overflow (String and final, Does it make sense to define a final String in Java?) but no one got around to answering this questions update question.

答:
At runtime, it does not make a difference.

The point is readability - as a member variable, it likely is declared at the beginning of the class' source code, and making it static means it doesn't have to be allocated for each new instance of the class.

Making it final signifies to the reader that the value will not change (to the compiler too, but that's less important here).

This way, there are no "magic values" buried in the implementation, and if a change is desired to the "constant", it only needs to be changed in one place.

This basically mimics what a C programmer would do with a #define.


问:
Improve coding quality
I have been dealing with programming for several years now (I am still a student but with a lot of internships). Mostly working with C++, Python and MATLAB, I noticed that whenever I download an SDK or a library from Internet/GitHub and look inside, the code is much more complex than mine, using error catches everywhere and other things that would never come to my mind while writing my own code. My question is, how can I learn or practice this kind of things? From my experience, no programming course talked about coding style, when and how to use try/catch efficiently, how to debug faster etc... I am also not thinking about using mutex while accessing one variable from different functions at the same time because my code is simply working without them and I didn't face any problem until now.

Currently I am working on a project using Python and Pycharm is helping me a lot keeping a correct coding style but it is limited to the syntax and naming conventions.

答: The most reliable way to get better is to practice. Not just do things, but strategically work at the border of your capabilities and then reflect on what works, what doesn't, and why.</p>

Title: Improve coding quality


问:
secure offline PC storage accessible through javascript
I'm attempting to build a browser-based HTML5 application that has the ability to store data locally on a PC (not mobile device) when offline. This data is sensitive and must be secure.

Of course the trick is trying to find a way to be able to access the secure data with Javascript.

I've ruled out browser local storage since its not secure. Could this be accomplished with a local database? If so, where could the DB credentials be stored? Javascript obviously doesn't seem like a good option to store them since its user-readable.

答: Maybe store data in the cookies encrypted?  Or use a 1x1 pixel flash app that talks with the javascript to do things javascript can't do, even talking to an Flash AIR app on the desktop using "LocalConnection" possibly, to give more access to the desktop.</p>


问:
Which management book would you recommend to read for a fresh Team Leader?
Which management book would you recommend to read for a fresh Team Leader?</p>

答: Read "The first 90 days..".. This book is indespensable..</p>


问:
Are there any benefits in not having referential integrity keys in database?
So Referential integrity is good, but are there scenarios where not having constraints is better?

For example when all the logic of relationships is kept in code? or when the database upgrade is simplified?

PS: I am not asking it is good not to have referential integrity, just that what scenarios would justify it

答:
There are several instances in which the performance and/or reliability of a system can be improved by loosening or eliminating referential integrity constraints:

Data warehouses and ad-hoc reporting databases. These may or may not need to deal with inconsistent data as another answer mentions. However, even if the data is consistent, it is usually much more efficient and reliable to import one table at a time, rather than one "entity root" at a time. Referential constraints can needlessly complicate matters when the business requirements for a decision-support database do not actually require real-time consistency.

Any systems with strict privacy rules, or systems which must support hard-deletion of master records for some other reason. You'll often need to support the deletion of all personally-identifiable customer information, but deleting all their transactions along with that customer will actually cause inconsistency from the business point of view, e.g. in accounting reconciliation. In these cases you generally want to keep that user ID - the fact that the user does not "exist" means the account was deleted. Of course, you could come up with a process wherein you replace all the user data with a stub, but it's a lot of extra work for no real benefit. Note that this scenario justifies removing some relational constraints but doesn't mean you should have none at all.

Complex hierarchies of data can incur serious performance hits with database-enforced referential integrity. Worse, since most database engines try to estimate an execution plan based on table statistics, this can result in deletions (or even some updates) taking several minutes to complete when there are only a couple of rows actually affected! DRI works best for master-detail type situations and maybe some 3-level hierarchies with very small tables (say a few million rows).

Very large tables in the billions of rows. DRI implies an index or constraint on the foreign key column, and if you don't actually need to query by this key, then the index can result in an enormous amount of wasted space - especially when you multiply by several constraints or several tables.

CQRS (Command-Query Responsibility Segregation) and/or event sourcing eliminate a lot of the traditional "future-proofing" benefit associated with DRI. This is similar but not identical to the point above. For example, let's say you've designed a billing system with the traditional order and order-detail tables. The order detail has a product ID and you actually do need to perform analysis on this - for example, correlating product purchases for use in a "customers who bought this also bought..." recommendation engine. However, in this case your architecture dictates that not only shouldn't you query the actual order detail table for this information, but you shouldn't query it at all - these are event tables that trigger downstream processes which create additional views of the data suitable for specific queries and reports. Having the indexes and referential constraints is a waste of resources because it doesn't guarantee anything of value - it won't help keep your query models in sync, but it will add significant overhead to the insertions, which is exactly what you need to optimize in a CQRS/event-sourcing architecture.

If your database needs to be partitioned (or better yet, distributed horizontally) for either performance or availability, you usually can't make any guarantees that the master and detail rows will always reside in the same "shard" - especially if there's a complex or even recursive set of relationships. It's just too hard a problem to solve, and if you could solve it, it might kill your entire partitioning strategy (e.g. billions of detail rows all reference the same master row 3 levels up in the hierarchy and therefore can't be partitioned...). That's part of the reason why there are a bunch of confusing rules concerning what combinations of partitioning, partition operations, and PKs/FKs are allowed. Distributed databases really don't play nice with referential integrity, which is why most nosql databases don't support it (i.e. because they are meant to be distributed).

This is just a few of the reasons off the top of my head... I'm sure I could come up with more, given time.

It's worth noting that all of these involve conscious decisions based on system architecture and probably considerable subject-matter expertise in your business domain. Laziness or ignorance aren't very good reasons, nor is the simplistic view of "it's faster that way!". It's faster until your data becomes inconsistent, at which point you'll end up sinking far more money into system maintenance than you would have originally invested into some higher-end hardware. It's really important that you have consistency and concurrency models in place; most systems that I've been exposed to which don't explicitly use DRI are using some form of optimistic concurrency and eventual consistency guaranteed by back-end durable messaging systems - the notable exception being data warehouses which are usually driven by ETLs instead.


问:
"Undoing" an integer wraparound
I ran into an interesting theoretical problem a number of years ago. I never found a solution, and it continues to haunt me when I sleep.

Suppose you have a (C#) application that holds some number in an int, called x. (The value of x is not fixed). When the program is run, x is multiplied by 33 and then written to a file.

Basic source code looks like this:

```<code>int x = getSomeInt();
x = x * 33;
file.WriteLine(x); // Writes x to the file in decimal format
</code>```

Some years later, you discover that you need the original values of X back. Some calculations are simple: Just divide the number in the file by 33. However, in other cases, X is large enough that the multiplication caused an integer overflow. According to the docs, C# will truncate the high-order bits until the number is less than int.MaxValue. Is it possible, in this case, to either:

Recover X itself or

Recover a list of possible values for X?

It seems to me (though my logic could certainly be flawed) that one or both should be possible, since the simpler case of addition works (Essentially if you add 10 to X and it wraps, you can subtract 10 and wind up with X again) and multiplication is simply repeated addition. Also helping (I believe) is the fact that X is multiplied by the same value in all cases - a constant 33.

This has been dancing around my skull at odd moments for years. It'll occur to me, I'll spend some time trying to think through it, and then I'll forget about it for a few months. I'm tired of chasing this problem! Can anyone offer insight?

(Side note: I really don't know how to tag this one. Suggestions welcome.)

Edit: Let me clarify that if I can get a list of possible values for X, there are other tests I could do to help me narrow it down to the original value.

答:
This maybe better suited as an question to Math (sic) SE. You are basically dealing with modular arithmetic, since dropping the left-most bits is the same thing.

I am not as good at Maths as the people who are on Math (sic) SE, but i will try to answer.

What we have here is that the number is being multiplied by 33 (3*11), and its only common denominator with your mod is 1. That is because by definition the bits in the computer are powers of two, and thus your mod is some power of two.

You will be able to construct the table where for every previous value you calculate the following value. And the question becomes do the following numbers correspond to only one previous one.

If it were not 33, but a prime or some power of a prime, i believe that the answer would be yes, but in this case… ask on Math.SE!

Programmatic test

This is in C++ because i don't know C#, but the concept still holds. This seems to show that you can:

```<code>#include <iostream>
#include <map>

int main(void)
{
    unsigned short count = 0;
    unsigned short x = 0;
    std::map<unsigned short, unsigned short> nextprev;

    nextprev[0] = 0;
    while(++x) nextprev[x] = 0;

    unsigned short nextX;
    while(++x)
    {
            nextX = x*33;
            if(nextprev[nextX])
            {
                    std::cout << nextprev[nextX] << "*33==" << nextX << " && " << x << "*33==" << nextX << std::endl;
                    ++count;
            }
            else
            {
                    nextprev[nextX] = x;
                    //std::cout << x << "*33==" << nextX << std::endl;
            }
    }

    std::cout << count << " collisions found" << std::endl;

    return 0;
}
</code>```

After populating such a map, you would be always able to get the previous X if you know the next one. There is only a single value at all times.

Title: "Undoing" an integer wraparound

Body:
This maybe better suited as an question to Math (sic) SE. You are basically dealing with modular arithmetic, since dropping the left-most bits is the same thing.

I am not as good at Maths as the people who are on Math (sic) SE, but i will try to answer.

What we have here is that the number is being multiplied by 33 (3*11), and its only common denominator with your mod is 1. That is because by definition the bits in the computer are powers of two, and thus your mod is some power of two.

You will be able to construct the table where for every previous value you calculate the following value. And the question becomes do the following numbers correspond to only one previous one.

If it were not 33, but a prime or some power of a prime, i believe that the answer would be yes, but in this case… ask on Math.SE!

Programmatic test

This is in C++ because i don't know C#, but the concept still holds. This seems to show that you can:

#include <iostream>
#include <map>

int main(void)
{
    unsigned short count = 0;
    unsigned short x = 0;
    std::map<unsigned short, unsigned short> nextprev;

    nextprev[0] = 0;
    while(++x) nextprev[x] = 0;

    unsigned short nextX;
    while(++x)
    {
            nextX = x*33;
            if(nextprev[nextX])
            {
                    std::cout << nextprev[nextX] << "*33==" << nextX << " && " << x << "*33==" << nextX << std::endl;
                    ++count;
            }
            else
            {
                    nextprev[nextX] = x;
                    //std::cout << x << "*33==" << nextX << std::endl;
            }
    }

    std::cout << count << " collisions found" << std::endl;

    return 0;
}

After populating such a map, you would be always able to get the previous X if you know the next one. There is only a single value at all times.


答:
One way to get it is to use brute force. Sorry I don't know C# but the following is c-like pseudo code to illustrate the solution:

```<code>for (x=0; x<=INT_MAX; x++) {
    if (x*33 == test_value) {
        printf("%d\n", x);
    }
}
</code>```

Technically, what you need is x*33%(INT_MAX+1) == test_value but integer overflow will automatically do the % operation for you unless your language uses arbitrary precision integers (bigint).

What this gives you is a series of numbers that may have been the original number. The first number printed would be the number that would generate one round of overflow. The second number would be the number that would generate two rounds of overflow. And so on..

So, if you know you data better you can make a better guess. For example, common clock maths (overflow every 12 o'clock) tend to make the first number more likely since most people are interested in things that happened today.

Title: "Undoing" an integer wraparound

Body:
I ran into an interesting theoretical problem a number of years ago. I never found a solution, and it continues to haunt me when I sleep.

Suppose you have a (C#) application that holds some number in an int, called x. (The value of x is not fixed). When the program is run, x is multiplied by 33 and then written to a file.

Basic source code looks like this:

```<code>int x = getSomeInt();
x = x * 33;
file.WriteLine(x); // Writes x to the file in decimal format
</code>```

Some years later, you discover that you need the original values of X back. Some calculations are simple: Just divide the number in the file by 33. However, in other cases, X is large enough that the multiplication caused an integer overflow. According to the docs, C# will truncate the high-order bits until the number is less than int.MaxValue. Is it possible, in this case, to either:

Recover X itself or

Recover a list of possible values for X?

It seems to me (though my logic could certainly be flawed) that one or both should be possible, since the simpler case of addition works (Essentially if you add 10 to X and it wraps, you can subtract 10 and wind up with X again) and multiplication is simply repeated addition. Also helping (I believe) is the fact that X is multiplied by the same value in all cases - a constant 33.

This has been dancing around my skull at odd moments for years. It'll occur to me, I'll spend some time trying to think through it, and then I'll forget about it for a few months. I'm tired of chasing this problem! Can anyone offer insight?

(Side note: I really don't know how to tag this one. Suggestions welcome.)

Edit: Let me clarify that if I can get a list of possible values for X, there are other tests I could do to help me narrow it down to the original value.

Body:
One way to get it is to use brute force. Sorry I don't know C# but the following is c-like pseudo code to illustrate the solution:

for (x=0; x<=INT_MAX; x++) {
    if (x*33 == test_value) {
        printf("%d\n", x);
    }
}

Technically, what you need is x*33%(INT_MAX+1) == test_value but integer overflow will automatically do the % operation for you unless your language uses arbitrary precision integers (bigint).

What this gives you is a series of numbers that may have been the original number. The first number printed would be the number that would generate one round of overflow. The second number would be the number that would generate two rounds of overflow. And so on..

So, if you know you data better you can make a better guess. For example, common clock maths (overflow every 12 o'clock) tend to make the first number more likely since most people are interested in things that happened today.


答:
To undo that result will give you a non-zero finite amount of numbers (normally infinite, but int is a finite subset of ℤ). If this is this acceptable, just generate the numbers (see other answers).

Otherwise you need to maintain a list of history (of finite or infinite length) of the variable's history.

Title: "Undoing" an integer wraparound


答:
Multiply by 1041204193.

When the result of a multiplication doesn't fit in an int, you won't get the exact result, but you will get a number equivalent to the exact result modulo 2**32. That means that if the number you multiplied by was coprime to 2**32 (which just means it has to be odd), you can multiply by its multiplicative inverse to get your number back. Wolfram Alpha or the extended Euclidean algorithm can tell us 33's multiplicative inverse modulo 2**32 is 1041204193. So, multiply by 1041204193, and you have the original x back.

If we had, say, 60 instead of 33, we wouldn't be able to recover the original number, but we would be able to narrow it down to a few possibilities. By factoring 60 into 4*15, computing the inverse of 15 mod 2**32, and multiplying by that, we can recover 4 times the original number, leaving only 2 high-order bits of the number to brute-force. Wolfram Alpha gives us 4008636143 for the inverse, which doesn't fit in an int, but that's okay. We just find a number equivalent to 4008636143 mod 2**32, or force it into an int anyway to have the compiler do that for us, and the result will also be an inverse of 15 mod 2**32. (We get -286331153.)

Title: "Undoing" an integer wraparound


问:
Writing a simple code validator
I know that programming languages can be defined in EBNF which can be converted into regular expressions. Right now I am working on a very simple BASIC interpreter for a project. The code has to be entered in a gui which should validate the syntax to later transfer the code to an embedded system where it is executed.

I was googling to find an article or tutorial on writing a validator for this job but I could not really find such a thing. Is it just defining the regular expressions and try to match them?

Note: the GUI part is written in Java while the embedded code is written in C++.

答:
Your initial premise that an EBNF language description can be converted to regular expressions is incorrect. The set of languages that can be parsed with regular expressions is a subset of the set of languages that can be described in EBNF.

For example, it is impossible to write a regular expression to check if nested parentheses are balanced.

The best way to validate your language input is to write a parser for it. There are also parser generators (a-la yacc/bison) for Java.

Title: Writing a simple code validator


问:
Ways for beginner programmer to practice with C++
So i just finished my first semester of college. In my intro to programming class we made a bunch of super interesting (sarcasm) console applications. Any suggestions on ways other than just messing around with console applications for a beginner C++ student to improve?

答:
Console applications may seem boring but they are essential to the development of the programmers ability to think of solutions. The basics of programming are always overlooked these days with the shiny stuff. I still use console applications a lot to test out ideas before building the high-level stuff on them. Once you have become good at the low-level stuff, you become a programmer with better understanding and flexibility and also have good programming habits.

Try challenging problems each time. I would recommend you Cracking the Coding Interview by Gayle Laakmann to get challenging questions and insights. You are at the best time in your career to start building up on these fundamentals and polishing them up into being a great programmer some day. Good luck.


答:
Well as soon as you write up some code and get it working, ask for a review on Code Review.SE. That's almost exactly what the site is for!

Plenty of people over there would be more than happy to get more rep help you write clean code.

Title: Improve coding quality

Body:
I have been dealing with programming for several years now (I am still a student but with a lot of internships). Mostly working with C++, Python and MATLAB, I noticed that whenever I download an SDK or a library from Internet/GitHub and look inside, the code is much more complex than mine, using error catches everywhere and other things that would never come to my mind while writing my own code. My question is, how can I learn or practice this kind of things? From my experience, no programming course talked about coding style, when and how to use try/catch efficiently, how to debug faster etc... I am also not thinking about using mutex while accessing one variable from different functions at the same time because my code is simply working without them and I didn't face any problem until now.

Currently I am working on a project using Python and Pycharm is helping me a lot keeping a correct coding style but it is limited to the syntax and naming conventions.


答:
Considering the error catches: do lots and lots of debugging, your own applications but also others. And also, let your programs be used by other people. They will do things in ways you never imagined.

If you only use your own code you will follow the pre-programmed path in your head and everything will go right.

Title: Improve coding quality


问:
How to develop cross platform mobile applications with native UI and Javascript backend?
I want to build a cross platform(Android, iOS, Windows) mobile application.

I want the UX of the application to be different on the different platforms so that it will be more platform specific and does not force different platform users to stick to a common UI, as this common UI might not gel well in terms of look and feel with other native applications in their platform.
However since it is the same application that I am trying to build across all platforms my backend will mostly be the same.

This image presents what I am trying to achieve.

Is it possible to build different UI for each platform using native technologies like Storyboard(in iOS), XML(in Android), XAML(in Windows)
and then bind these UI elements to native controllers.
And making this controller use a common javascript backend for all the platforms.

I am aware of the concept of Native and Hybrid applications.
The problem that I would face with them are the following

Pure native applications will force me to make the entire source code platform specific which will make me write my backend thrice in 3 different languages. (Least reusable)

Hybrid applications(like those build on PhoneGap) will let me write my code in javascript and html but will create a common ui with HTML5/CSS3 which should be used across all platforms, I want to have different UI and for the UI to be more native than generic.

Is this common javascript backend code achievable.
And if it is then is there a way in which I can create this entire javascript code independently and package it as platform specific libraries like .a(for iOS), .jar(for Android), .dll(for Windows).
Or should I use some other approach?

Thanks in Advance

答:
To 1:
I know that Xamarin has a proprietary way based on their implementation of .NET. You can use one language to build the common application backend and there are wrappers for the native libraries. They share the philosophy of building the GUI with the native libraries. It is not javascript though.</p>


答:
A general rule of thumb when using some external library (which you always do in application programming, at least using the standard C library in C) is to check for failure of most functions you are calling.

A typical simple example is stdio(3) and <stdlib.h> functions. You certainly should always check when using fopen(3) (or popen(3)) and malloc(3). So don't code

```<code> /// BAD SINCE NO CHECKS
 FILE* fil = fopen("outfile.txt", "w");
 fprintf (fil, "something, e.g. one is %d\n", 1);
</code>```

But at the very least:

```<code> FILE* fil = fopen("outfile.txt", "w");
 if (!fil) { perror("fopen outfile.txt"); exit(EXIT_FAILURE); };
 fprintf (fil, "something, e.g. one is %d\n", 1);
</code>```

and likewise coding simply

```<code> /// BAD SINCE NO CHECKS
 struct somestruct_st *ptr = malloc(sizeof(struct somestruct_st));
 ptr->somefield = 2;
</code>```

is wrong, you should at least:

```<code> struct somestruct_st *ptr = malloc(sizeof(struct somestruct_st));
 if (!ptr) { perror("malloc somestruct_st"); exit(EXIT_FAILURE); };
 ptr->somefield = 2;
</code>```

There are some functions which you could test but you often don't. A typical example is fclose(3). If you are very careful you should test it, but I usually don't.

Notice that testing corner cases failures (like above) may be hard. On Linux, lowering disk quotas and limits (with setrlimit(2) ...) may help, since you could almost force some of these failures.

Notice that server software (which runs many days) should take more care about detecting and reporting error than a simple commandline tool.

For critical embedded software (like your heart pacemaker, your airline aircraft) checking all cases is essential. static program analysis may help (but is not a silver bullet).

Also, study the source code of (and contribute to) existing free software. It will teach you a lot. And learn several programming languages (certainly Ocaml or Haskell, Scheme or CommonLisp will teach you a lot!).

Take also time to read the documentation of the functions or libraries that you are using.

Title: Improve coding quality

Body:
A general rule of thumb when using some external library (which you always do in application programming, at least using the standard C library in C) is to check for failure of most functions you are calling.

A typical simple example is stdio(3) and <stdlib.h> functions. You certainly should always check when using fopen(3) (or popen(3)) and malloc(3). So don't code

 /// BAD SINCE NO CHECKS
 FILE* fil = fopen("outfile.txt", "w");
 fprintf (fil, "something, e.g. one is %d\n", 1);

But at the very least:

 FILE* fil = fopen("outfile.txt", "w");
 if (!fil) { perror("fopen outfile.txt"); exit(EXIT_FAILURE); };
 fprintf (fil, "something, e.g. one is %d\n", 1);

and likewise coding simply

 /// BAD SINCE NO CHECKS
 struct somestruct_st *ptr = malloc(sizeof(struct somestruct_st));
 ptr->somefield = 2;

is wrong, you should at least:

 struct somestruct_st *ptr = malloc(sizeof(struct somestruct_st));
 if (!ptr) { perror("malloc somestruct_st"); exit(EXIT_FAILURE); };
 ptr->somefield = 2;

There are some functions which you could test but you often don't. A typical example is fclose(3). If you are very careful you should test it, but I usually don't.

Notice that testing corner cases failures (like above) may be hard. On Linux, lowering disk quotas and limits (with setrlimit(2) ...) may help, since you could almost force some of these failures.

Notice that server software (which runs many days) should take more care about detecting and reporting error than a simple commandline tool.

For critical embedded software (like your heart pacemaker, your airline aircraft) checking all cases is essential. static program analysis may help (but is not a silver bullet).

Also, study the source code of (and contribute to) existing free software. It will teach you a lot. And learn several programming languages (certainly Ocaml or Haskell, Scheme or CommonLisp will teach you a lot!).

Take also time to read the documentation of the functions or libraries that you are using.


问:
Relation between projects and solutions in VS
We're about to start with a new software and there are mixed opinions on the organization of software. I'd be delighted to hear what others might have to say in regard to the presented options as well as what other consideration one might refer to when making such a decision.

Hierarchical approach

Interchangeable approach

Approach #1 would consist of a single solution in VS with a number of projects connected to it (such as Utilities, Service, Exporter, Gui etc.). Everything would be in a single collection and the same root directory (for the solution file) and subdirectories (for the project files), so to speak.

Approach #2 would be constituted primarily of a set of projects, not related to each other (other than the references, of course), while the solution's (or solutions', would we desire to create different setups for different deliveries) purpose would be solely to refer to the (external) projects collecting them in the GUI. There would be n+1 directories (one for each project's file and an additional one for the solution's file, or solutions' files later on).

We've discussed the matter and listed the advantages of each approach and, although agreed on the facts, the team's members are not on the same page regarding which one to choose. We're a very democratic organization, so the decision needs to be persuasive to everybody (or at least a vast majority) and there won't be any from-above order from the boss. There's no prior code base and the financial consideration needs not to be addressed.

Which approach is preferable? Which is more of a commonly applied standard in the industry? What considerations might one take to ensure the rigidity of the choice?

It's also fully possible that our current project will be subject to the situation described in this question - both being the one that "borrows" projects from elsewhere as well as being the one that the projects are "borrowed" from.

答:
It depends... its all about dependency management.

You're going to have a lot easier time with a single solution. This is so you can simply reference the other projects within a project and it'll all build and will be up to date everytime. This approach doesn't scale though.

So the problem is entirely down to those pesky references. The biggest problem I found was that the paths to external references (ie not part of the solution) were relative. So your team members must checkout a library in the same position in the build tree as it was originally created. If you can live with this restriction, building individual projects will be viable.

However, today Microsoft is using NuGet as a way to deliver libraries to applications. You build a lib, package it as NuGet and deploy it to a server. Then, when an application wants to use this library, it will automatically fetch it. No more compiling, you can always get the latest version from the build server (you so have CI, if not - get Jenkins. OSS/free and awesome).

This means you can concentrate on your part of the application rather than the dependencies. It also means you'll be more likely to keep a good separation of concerns in these libraries.


答:
Code validation should not only be syntactical, but more importantly should take some of the semantics, which is much harder. Read about static program analysis, type inference, etc...

For your project, did you consider embedding an existing interpreter (e.g. guile or Lua, etc...) inside your program?

If you want to write an interpreter, read about domain specific languages. See also this answer to a related question.

Title: Writing a simple code validator

Body:
I know that programming languages can be defined in EBNF which can be converted into regular expressions. Right now I am working on a very simple BASIC interpreter for a project. The code has to be entered in a gui which should validate the syntax to later transfer the code to an embedded system where it is executed.

I was googling to find an article or tutorial on writing a validator for this job but I could not really find such a thing. Is it just defining the regular expressions and try to match them?

Note: the GUI part is written in Java while the embedded code is written in C++.


问:
Can a closed-source programming language survive?
A friend has written a programming language. It has a syntax reminiscent of SGML. He has written an interpreter for it, and an IDE. He and his colleagues use it in-house as a server-side language. It can also be used to write command-line tools.

He wants to make it available to the public, in the expectation that people will purchase a license to use it. He wants to keep the code expressing the language implementation to himself, as there's a fair bit of intellectual property tied up in it.

I keep telling him that the day of closed-source programming languages is gone. I say, "Look at all the major languages: the vast majority are open-source. You're going to have to go open-source too if you want anyone outside the company to pay any attention to what you've built."

Am I giving him good advice or is there still room for proprietary languages that you pay
for?

LATER

Den asked, "... could you please also explain how a language can be closed-source?"

I said, "@Den you make a good point. What my friend wants to avoid, I suppose, is the situation where Microsoft cooks up a Java-alike language, calls it J++ and then gets into litigation with Sun about its Java-ness. How do you protect a syntax and a programming methodology from being hijacked by a company whose implementation could put you out of business?"

答:
Does his language do something that enough people will pay for?

That's really the only thing that decides whether a business model will work. Do you have a large market of users who are large enough not to worry about licensing costs? Does the language support devices or standards that the customers can't live without, and that nothing else supports? Is it so insanely great that the customers will be able to hire the greatest, brightest programmers and achieve huge productivity increases just by using this language, and does management understand that trade-off?

If any of these or anything comparable is the case, then the business model will probably work. Otherwise, it probably won't: sooner or later, someone is going to come up with a cost-cutting measure that involves switching to a cheaper alternative.


答:
I believe that no, there is no room for a new language with a proprietary implementation sold by a small company.

First, developers have many other free (at least as "in beer", and often as "in speech") language implementations, and they won't bother trying a (pricy) language.

Second, any manager would immediately objects: what would happen -to our code base coded in the new language- if the small company providing the language implementation get bankrupt? This argument probably would prohibit anyone to buy the language implementation!

In contrast, a free software language implementation can be grossly evaluated by customers, which could always handle its service to another provider, if the original company having written it goes bankrupt.

From the client's perspective, the cost of adopting a new language is not in the licence of the implementation, but in the skills required to use it.

And there are many free software language implementations which are nearly unused.

Title: Can a closed-source programming language survive?

Body:
A friend has written a programming language. It has a syntax reminiscent of SGML. He has written an interpreter for it, and an IDE. He and his colleagues use it in-house as a server-side language. It can also be used to write command-line tools.

He wants to make it available to the public, in the expectation that people will purchase a license to use it. He wants to keep the code expressing the language implementation to himself, as there's a fair bit of intellectual property tied up in it.

I keep telling him that the day of closed-source programming languages is gone. I say, "Look at all the major languages: the vast majority are open-source. You're going to have to go open-source too if you want anyone outside the company to pay any attention to what you've built."

Am I giving him good advice or is there still room for proprietary languages that you pay
for?

LATER

Den asked, "... could you please also explain how a language can be closed-source?"

I said, "@Den you make a good point. What my friend wants to avoid, I suppose, is the situation where Microsoft cooks up a Java-alike language, calls it J++ and then gets into litigation with Sun about its Java-ness. How do you protect a syntax and a programming methodology from being hijacked by a company whose implementation could put you out of business?"


问:
The physical implementation of quantum annealing algorithm
From that question about differences between Quantum annealing and simulated annealing, we found (in comments to answer) that physical implementation of quantum annealing exists (D-Wave quantum computers).

Can anyone explain that algorithm in terms of quantum gates and quantum algorithms, or in physical terms (a part of algorithm that depends on quantum hardware)?

答:
This question should probably go to physics.SE but just as a warning: The D-Wave quantum computer might not really give any speed advancement, because.. something is wrong. So there might not be any physical implementation available so far.

See: Quantum or not, controversial computer yields no speedup, Adrian Cho, Science, 20, 2014, Link


问:
Organizing Business and Presentation entities
Background

I am developing a WPF project.

This is the basic structure:

User Interface (WPF Project);

Interfaces (class library, contains all the interfaces and the entities used by the application;

Modules (every module contains the logic of a specific argument, e.g. File Management, and can eventually contains Wpf User Controls).

In the WPF Controls, to facilitate the binding operations I have created a BaseViewModel class which contains a Raise method that automates the binding mechanism (for further details, I used a technique similar to that one described in this article).

The problem

Understand which is the best way to separate Presentation form from the Business form in the entities classes.

The case

In the Interfaces project I have, for instance, the class User

```<code>public class User
{
    public virtual string Name { get; set; }

    // Other properties
}
</code>```

In one of the modules I need to use the User class and to bind its properties to the User Interface controls. To do so I have to use a custom implementation of the get and set keywords.

At first point, I thought to create a class in the Module called, for instance, ClientUser and override the properties that I need:

```<code>public class ClientUser : User
{
    private string name;

    public override string Name { get { return name; } set { Raise(out name, value); } }

    // Other properties
}
</code>```

The problem is the Raise method, which is declared in the BaseViewModel class, but due to C# single inheritance constraint, I can't inherit from both classes.

Which is the right way to implement this architecture?

答:
Use interfaces

```<code>public interface IUser
{
    string Name { get; set;}
}
</code>```

And now you can have two implementations,

```<code>public class User : IUser
{
    public string Name { get; set; }
}
</code>```

and

```<code>public class ClientUser : BaseViewModel, IUser
{
   private string _name;
   public string Name
   {
       get
       {
           return _name;
       }
       set
       {
          Raise(out _name, value);
       }
   }
</code>```

}

As a positive side effect, you got rid of the virtual.

If your client user is simply a viewmodel for a user entity (which it seems to be), you most likely want a different design. Given IUser and User from above, you would write a viewmodel class:

```<code>public UserViewModel : BaseViewModel
{
    private readonly IUser _user;
    UserViewModel(IUser user)
    {
        _user = user;
    }

    public string Name
    {
       get
       {
           return _user.Name;
       }
       set
       {
          _user.Name = value;
          Raise(out _name, value);
       }
   }

}
</code>```

OwnerDisplayName: simoneL

Body:
Use interfaces

public interface IUser
{
    string Name { get; set;}
}

And now you can have two implementations,

public class User : IUser
{
    public string Name { get; set; }
}

and

public class ClientUser : BaseViewModel, IUser
{
   private string _name;
   public string Name
   {
       get
       {
           return _name;
       }
       set
       {
          Raise(out _name, value);
       }
   }

}

As a positive side effect, you got rid of the virtual.

If your client user is simply a viewmodel for a user entity (which it seems to be), you most likely want a different design. Given IUser and User from above, you would write a viewmodel class:

public UserViewModel : BaseViewModel
{
    private readonly IUser _user;
    UserViewModel(IUser user)
    {
        _user = user;
    }

    public string Name
    {
       get
       {
           return _user.Name;
       }
       set
       {
          _user.Name = value;
          Raise(out _name, value);
       }
   }

}


答:
The answer is yes, and no. It depends on the commercial motivations of potential customers and the attributes of the language and the problems it solves.

No, the world does not need another general purpose computing language created by an individual or a small team. When Perl, Python, Ruby, Java and Javascript and were created there was a vacuum to fill, proprietary languages were expensive and the barrier to entry was low. Rebol is one that started off paid and is now free. Look at C# and Go to see how much harder it is now and how much bigger the teams are, even for languages that are more or less free.

But yes, the world badly needs niche languages to fill a whole range of specific roles and will pay well for them. I can't quote you examples because neither you nor I have ever heard of most of them, but they are being used routinely in highly specialised situations and they make money for their creators. Solve a problem and you will get paid.

So for your friend to make money he needs one or more of three things.

An identifiable technical niche for which his language is the best available solution, preferably with a reasonably high barrier to entry to slow down competitors.

An identifiable customer segment with a problem his language can solve as well as the capacity to pay for it to be solved.

A body of pre-written code, documentation, tutorials and skills that will allow customers to put it to work immediately and start solving problems immediately.

Problems mentioned in relying on small companies are not unique to programming languages, and are easily resolved by commercial means.

Disclosure: I am the author of a commercial programming language system (Powerflex) that helped a lot of people build software businesses. That window closed as the Internet window opened.


答:
A language isn't open-source or closed-source as such. For example, G++ is open source while MSVC++ is closed source. ISO C++ is neither, it's a non-free non-proprietary standard.

Your friend could release an Open-Source non-optimizing implementation, and sell the fancy optimizing compiler. The interesting Intellectual Property is not going to be needed for a straightforward implementation.

An existing language which works with this model is PHP/Zend Server


答:
I think the answer is a definite no in this case. Having a new language driven by a small entity causes a high risk of critical bugs or key features missing.

If that language is proprietary, then as a user you're absolutely screwed if the language does not evolve in the direction you need it to at the pace you need it to. If the language is free, you can throw money or man power at the problem (which at least for bigger companies is an option).

Your friend would be far better off selling complementary services or products. Provide support, training, consulting. Get paid for adding specifically requested features. Provide tooling (e.g. in the form of commercial plugins for popular IDEs). Provide some libraries under a commercial licensing model (but still with the source included under suitable restrictions).


问:
Is a book that teaches how to build compilers good for learning to implement interpreters?
I'm looking for a book to learn how to implement interpreters for programming languages. Thing is there are much more 'compiler books' than 'interpreter books'. So my question is: can I read a book that teaches how to build compilers, to learn how to build interpreters (at a very beginner level)? Is this a good idea? If so, what do I need to keep in mind while reading?</p>

答:
Absolutely - an interpreter is just a "one line at a time" compiler. It performs much the same task, that of taking some form of human-understandable source code and turning it into something a computer processor can understand. A compiler will do this for entire source file(s), whereas an interpreter will do this on an as-read basis.

You will need to handle a few differences around loading source as needed, and handling parsing source files to find the next line to read, but otherwise you'll be implementing a compiler fundamentally.


答:
You could the SMT solver Z3 to ask it to give you a satisfying assignment for the formula x * 33 = valueFromFile. It will invert that equation for you and give you all possible values of x. Z3 supports exact bitvector arithmetic including multiplication.

```<code>    public static void InvertMultiplication()
    {
        int multiplicationResult = new Random().Next();
        int knownFactor = 33;

        using (var context = new Context(new Dictionary<string, string>() { { "MODEL", "true" } }))
        {
            uint bitvectorSize = 32;
            var xExpr = context.MkBVConst("x", bitvectorSize);
            var yExpr = context.MkBVConst("y", bitvectorSize);
            var mulExpr = context.MkBVMul(xExpr, yExpr);
            var eqResultExpr = context.MkEq(mulExpr, context.MkBV(multiplicationResult, bitvectorSize));
            var eqXExpr = context.MkEq(xExpr, context.MkBV(knownFactor, bitvectorSize));

            var solver = context.MkSimpleSolver();
            solver.Assert(eqResultExpr);
            solver.Assert(eqXExpr);

            var status = solver.Check();
            Console.WriteLine(status);
            if (status == Status.SATISFIABLE)
            {
                Console.WriteLine(solver.Model);
                Console.WriteLine("{0} * {1} = {2}", solver.Model.Eval(xExpr), solver.Model.Eval(yExpr), solver.Model.Eval(mulExpr));
            }
        }
    }
</code>```

Output looks like this:

```<code>SATISFIABLE
(define-fun y () (_ BitVec 32)
  #xa33fec22)
(define-fun x () (_ BitVec 32)
  #x00000021)
33 * 2738875426 = 188575842
</code>```

Title: "Undoing" an integer wraparound

Body:
You could the SMT solver Z3 to ask it to give you a satisfying assignment for the formula x * 33 = valueFromFile. It will invert that equation for you and give you all possible values of x. Z3 supports exact bitvector arithmetic including multiplication.

    public static void InvertMultiplication()
    {
        int multiplicationResult = new Random().Next();
        int knownFactor = 33;

        using (var context = new Context(new Dictionary<string, string>() { { "MODEL", "true" } }))
        {
            uint bitvectorSize = 32;
            var xExpr = context.MkBVConst("x", bitvectorSize);
            var yExpr = context.MkBVConst("y", bitvectorSize);
            var mulExpr = context.MkBVMul(xExpr, yExpr);
            var eqResultExpr = context.MkEq(mulExpr, context.MkBV(multiplicationResult, bitvectorSize));
            var eqXExpr = context.MkEq(xExpr, context.MkBV(knownFactor, bitvectorSize));

            var solver = context.MkSimpleSolver();
            solver.Assert(eqResultExpr);
            solver.Assert(eqXExpr);

            var status = solver.Check();
            Console.WriteLine(status);
            if (status == Status.SATISFIABLE)
            {
                Console.WriteLine(solver.Model);
                Console.WriteLine("{0} * {1} = {2}", solver.Model.Eval(xExpr), solver.Model.Eval(yExpr), solver.Model.Eval(mulExpr));
            }
        }
    }

Output looks like this:

SATISFIABLE
(define-fun y () (_ BitVec 32)
  #xa33fec22)
(define-fun x () (_ BitVec 32)
  #x00000021)
33 * 2738875426 = 188575842


答:
Is a book that teaches how to build compilers good for learning to implement interpreters?

Yes - A good book on compilers will cover a wide range of topics, many of which are directly relevant to interpreters / interpreted languages.  For example:

lexical analysis

parsing

creation of an AST

type checking, identifier resolution and other kinds of semantic analysis

"compiler" error reporting

possibly ... generation of an abstract machine code that the interpreter will "execute".

If so, what do I need to keep in mind while reading?

Keep in mind that some of the material in the book may not be that relevant.  For example, a typical abstract machine is register-less, so the sections of the book on register allocation during code generation are typically not relevant to an interpreter.

(But that's just common sense.  You wouldn't normally read a book like that from cover to cover.  You'd typically skim the bits that don't seem relevant to your goals.)

Body: I'm looking for a book to learn how to implement interpreters for programming languages. Thing is there are much more 'compiler books' than 'interpreter books'. So my question is: can I read a book that teaches how to build compilers, to learn how to build interpreters (at a very beginner level)? Is this a good idea? If so, what do I need to keep in mind while reading?</p>


问:
Is recursion an instance of being "too clever" when programming?
I've read several books and learned through experience that optimizing code to the point where it is inscrutable, or coming up with an extremely fast but extremely complex solution to a problem is not desirable when working in teams, or even when you're working by yourself and have to understand your clever solution some time later.

My question is, should recursion be treated in the same manner?  Does the average programmer understand recursion easily and thus one should use it with impunity, or does the average programmer not understand recursion very well and one should stay away from it for the sake of overall team productivity?

I know there are simple answers of, "Any programmer who doesn't understand recursion isn't worth a grain of salt, so don't worry about them" but I was wondering if you all had some real world experience you would like to share that would illuminate the issue more than the opinion I just mentioned.

答:
Does the average programmer understand recursion easily and thus one should use it with impunity, or does the average programmer not understand recursion very well and one should stay away from it for the sake of overall team productivity?

I'd say that the average programmer understands recursion perfectly.  Indeed, if the programmer has done a degree in Computer Science or Software Engineering it is pretty much guaranteed.  Granted, there are some very below average programmers out there, but you don't want them on your team.

In this case, the distinction between an average and a good programmer is knowing when to use recursion and when not to.  And that depends on the problem being solved AND the language being used to solve it.

If you are using a functional programming language, recursion is a natural and efficient solution for a wide range of problems.  (Tail recursion optimization rules!)

If you are using an OO or plain procedural language, recursion can be inefficient and can be problematic due to stack overflows.  So in some cases you would choose an iterative solution rather than a recursive one.  However, in other cases, the recursive solution is so much more simple and elegant that the (possibly more efficient) iterative solution would be the "too clever" one.  (For example, if the problem requires backtracking, building or walking trees / graphs, etc, recursion is often simpler.)


答: While I hate to discourage your friend I think it's unlikely that he'll manage to convince people to pay for development tools these days unless this tool provides an incredibly huge gain in productivity (as in "produces working software by having managers look cross-eyed at the screen while thinking good thoughts!!!"). For better or worse there is very little market for "pay-for-play" development tools these days as the quantity and quality of free tools is excellent. (Witness languages such as Java, Ruby, Python, Clojure - IDE's such as Eclipse and LightTable - databases such as MySQL and PostgreSQL - the list goes on and on and on and on and on...). I wish him the very best of luck with this endeavor.</p>


答:
I've had this discussion myself when one of my clients considered developing major applications using ColdFusion. Personally I can't think of any reason to use CF (and pay for it) when I can use PHP (and not pay for it). However, CF has a large company behind it which pacifies the OSS-phobiacs (deal with enough IT managers and you're bound to run across some of those eventually) and it good enough that enough developers actually prefer it.

However, the catch is, of course, that your friend needs to come up with something good enough and with enough backing behind it. The former is no mean trick these days with all the thoroughly mature open source platforms around, and the latter requires backing of a party at least the size, of, say, Adobe.

Not to mention the fact that even CF has a marginal market share these days in comparison to OSS.

In summary, if your friend is brilliant enough to come up with something that outshines PHP, Python and friends and business savvy enough to sell it to one of the larger and more reputable players in the market, the answer is "maybe". Otherwise, it's a resounding "no".


答:
A language cannot be closed-source. Its compiler and run-time libraries can be closed-source. A formal grammar of a language can be kept as a secret though and be legally protected (NDAs, etc.) and fees collected for usage.

Your friend could claim intellectual property or patent if the language is so new and novel. I myself have high doubt that this would worth the effort.

These days, most of the companies choose publicly available technologies first, no matter how much laborious work it is to achieve the same effect a closed-source approach would do. Next, if the overhead is super large, then they go to an industry standard solution - standardized proprietary languages (e.g. Matlab), with good penetration and support.

In-house languages are usually built as DSLs (domain specific languages), and these days the effort is smaller than buying a DSL of somebody else's and adapt it. Also, DSLs are very specific to the problem domain.

Now, let's not discourage your friend from monetizing his language. There are ways to do this - selling it to a large, established company, or getting some investors buy the idea and invest in it -, but his main problem in approach is that he developed a solution without researching the development problem. And that is not the problem what he considers the problem, it is what his potential customers consider the problem. So he could go out and talk with these fellows without giving out details about his solution and get those guys to pay - this is not impossible but not very likely though.


问:
What is the benefit of the 'free-to-deobfuscate' model over open-source?
Some applications (for example Minecraft) have the 'free-to-deobfuscate'-model. It means that you are free to make and distribute changes to the applications code, but you must decompile and deobsuscate the application first.

This makes less than zero sense to me. Isn't the whole point of obfuscation the prevention of people messing with your code? Why not just use the open-source model?

答:
Minecraft is not open source. You are not allowed to distribute it in any way, in particular you are not allowed to sell it or a modified version of it. Minecraft is closed source.

There were rumours that Minecraft might become open source at some point but so far this hasn't happened.

What Minecraft however allows is for the user to modify it and to distribute the modification among other users. They seem to allow de-compilations of the java bytecode (which also works much better than de-compiling C code for example). However they (since Minecraft is closed source) do not publish the source code. Legally they could because their EULA is already restrictive but for practical reasons they don't want to do it.

The benefit is clear: more modifications made by users increases the appeal of the product and the profit they make.


问:
Declaring variables in Python and PHP
The question is how to cope with absence of variable declaration in Python, PHP, and the like.

In most languages there is a way to let the compiler know whether I introduce a new variable or refer to an existing one: my in Perl (use strict) or \newcommand vs. \revewcommand in LaTeX. This prevents from two major sources of errors and headache:

(1) accidentally using the same name of a variable for two different purposes, such as in (PHP)

```<code>$v = $square * $height;
<...lots of code...>
foreach ($options as $k => $v)
    echo "For key $k the value is $v\n";
<...lots of code...>
echo "The volume is $v";
</code>```

or a lot nastier (PHP)

```<code>$a = [1, 2, 3];
foreach ($a as $k => &$v)
    $v++;
foreach ($a as $k => $v)
    echo "$k => $v\n";
</code>```

(can you see a bug here? try it!); and

(2) prevent from typos (PHP):

```<code>$option = 1;
$numberofelements = 1;
if ($option)
{
    $numberofelenents = 2;
}
echo $numberofelements;
</code>```

(can you see a bug here? PHP will execute silently).

Using something like my (Perl)

```<code>use strict;
my $option = 1;
my $numberofelements = 1;
if ($option)
{
    $numberofelenents = 2;
}
say $numberofelements;
</code>```

(Perl will immediately report the bug) is a tiny effort and HUGE benefit both in debug time and (much more importantly) in losses (potentially huge) from incorrect programs.

However, some languages, notably Python, PHP, and JavaScript, do not give any protection from these types of bugs.

My question is how can we effectively cope with this?

The only way I can foresee is to create two functions (PHP):

```<code>function a ($x)
{
    if (isset ($x))
        die();
    else
        return &$x;
}
</code>```

and

```<code>function the ($x)
{
    if (isset ($x))
        return &$x;
    else
        die();
}
</code>```

and use them always:

```<code>a($numberofelements) = 1;
the($numberofelenents)++;
say the($numberofelements);
</code>```

but of course this is extremely cumbersome. Any better way of effectively protecting from such errors?

No, "use another language", "be careful and don't make errors", and "split your code in tiny functions" are not good answers (the latter may protect from the errors of type 1 but not type 2).

答:
There's only 3 solutions:

Accept that you will occasionally have bugs because of this and deal with them as they occur

Use a lint/static analysis tool (e.g. pylint)

Use another language

Title: Declaring variables in Python and PHP


问:
Why is polling accepted in web programming?
I am currently working on a Ruby on Rails project which shows a list of images.

A must-have for this project is that it shows new posts in realtime without the need of refreshing the web page. After searching for a while, I've stumbled upon some JavaScript solutions and services such as PubNub; however, none of the provided solutions made sense at all.

In the JavaScript solution (polling) the following happens:

User 1 views the list of photos.

In the background the JavaScript code is polling an endpoint every second to see if there is a new post.

User 2 adds a new photo.

There is a delay of 50 ms before the new cycle is triggered and fetches the new data.

The new content is loaded in the DOM.

This seems odd when translated to a real world example:

User 1 holds a pile of pictures on his/her desk.

He/she walks to the photographer every second and asks if he has a new one.

The photographer makes a new photo.

This second when he/she walks in, she can take the picture and put it on the pile.

In my opinion the solution should be as following:

User 1 holds a pile of pictures on his/her desk.

The photographer takes a new picture.

The photographer walks to the pile and puts it with the rest.

The PubNub solution is basically the same, however this time there is an intern walking between the parties to share the data.

Needless to say, both solutions are very energy consuming as they are triggered even when there is no data to load.

As far as my knowledge goes there is no (logic) explanation why this way of implementation is used in almost every realtime application.

答:
The question is to balance the amount of unnecessary polls vs the amount of unnecessary pushes.

If you poll:

You get an answer at this very moment. Good if you ask only occasionally or need a data set this very moment.

You might get a "no content" answer, causing pointless load on the line.

You put load on the line only when you poll, but always when you poll.

If you push:

You deliver the answer right when it is available, which allows an immediate processing on the client side.

You might deliver data to clients which are not interested in this data, causing pointless load on the line.

You put load on the line every time there is new data, but only when there is new data.

There are several solutions on how to deal with the various scenarios and their disadvantages, like for example a minimum time between polls, poll-only proxies to take the load off the main system, or - for the pushes - a regulation to register and specify the wanted data followed by unregistering on log-off. Which one fits best is nothing you can say in general, it depends on the system.

In your example polling is not the most efficient solution, but the most practical one. It is very easy to write a polling system in JavaScript, and it is very easy to implement it on the delivery side as well. A server made to deliver image data should be able to handle the extra requests, and if not, it can be scaled linearly, as the data is mostly static and can therefore be easily cached.

A push method implementing a log-in, description of wanted data and finally a log-off would be most efficient, but is probably too complex for the average "script-kiddy", and needs to deal with the question: what if the user just shuts down the browser and log-off cannot be performed?

Maybe it is better to have more users (as accessing is easy) than to save some bucks on another cache-server?


问:
How should I remember what I was doing and why on a project three months back?
I was working on a project three months back, and then suddenly another urgent project appeared and I was asked to shift my attention.

Starting tomorrow, I'll be heading back to the old project. I realize that I do not remember what exactly I was doing. I don't know where to begin.

How can I document a project such that anytime I look back it shouldn't take me more than a few minutes to get going from wherever I left. Are there best practices?

答:
This is not intended to be a complete answer—there are already several very good ones mentioning important things like how to use your VCS and your project management software—but rather an addendum adding a few points I did not see in any others, which I find to be very helpful, and which I hope other people might find helpful as well.

1. No task is too soon or too small to write down

People usually make TODO lists for things that they plan to do in the future, but since programming requires concentration, and since we can be interrupted at any time, I've found it helpful to write down even what I'm doing right now, or what I'm about to start in a matter of seconds.  You may feel you're in the zone and you couldn't possibly forget the solution that just hit you in that aha moment, but when your co-worker drops by your cube to show you a picture of his infected toe, and you are only able to finally get rid of him by starting to gnaw on your own arm, you may wish you had written down a quick note, even if only on a Post-It™ note.

Of course some other more persistent medium might be better (I'm particularly fond of OmniFocus), but the point is to at least have it somewhere, even if you'll finish in 20 minutes and then throw the Post-It™ away.  Although you may discover that that information becomes useful, to put on time sheets or invoices to the client, or when your boss/client asks you what you've been working on and you can't remember.  If you drop all of these notes in a box or drawer or folder, then when a big interruption hits—an interrupting project—then you can glance through them and remember a lot of the things you did to get your code to the point where you find it when you return to the project.

2. Use a whiteboard at your desk to capture big-picture ideas

I have a 3" x 4" whiteboard next to my desk, so when I start a project I can brainstorm the solutions to all the problems I perceive in a project.  It could be architectural diagrams, use cases, lists of risks and obstacles, or anything that seems relevant to you.

Some more formalized approaches require you to generate diagrams and use cases and so forth as "deliverables" in some paper or electronic format, but I find that that can create a lot of extra work, and just become a series of sub-projects that end up being divorced from the actual purpose of the main project, and just part of a formalized process that you have to do but that no one pays much attention to.  A whiteboard is the simplest thing that actually works, at least in my experience.  It is as persistent as you want (with a camera) and most importantly allows you to get your ideas down immediately.

I think better with a pen in my hand, so dumping my thoughts onto a white surface comes naturally to me, but if you don't find that to be the case for you, here are some questions that may help you decide what is relevant:

If I were the lead developer, about to go on a honeymoon for 3 months while other developers completed the project, what general direction would I want to give them?  What ideas would I want to make sure they knew about, or approaches would I want to ensure they took?  What libraries or other helpful solutions would I want to be sure they were aware of?

If this project were my million-dollar idea that I knew would ensure my future financial independence, but I was scheduled for a critical surgery that would incapacitate me for 3 months, what would I want my future self to have, to ensure successful completion of the project?

(When I first scribble ideas down, I only worry about them making sense to my present self.  Once they are down I can look more critically at them and make changes to ensure they make sense to my future self or to others.  Worrying too much about communicating to others as you write them down initially can lead to writers' block—a mind clogged by competing goals.  Get it down first; worry about clarity later.)

I recommend you spend the money to buy a decent whiteboard, at least 3" x 4", and hang it up in the space where you normally work.  There are many advantages of a physical whiteboard over any virtual system.

It is large.  By taking up a lot of space it makes its presence felt, and the plans on it feel like they are a part of you workspace, helping to point you in the right direction all the time.

It is there persistently: you don't have launch a certain app or web site to access it, and you won't risk forgetting how to get to it, or forgetting that it's there.

It is immediately accessible when you have an idea that you want to think through.

You lose many of the benefits if you just use a whiteboard in a meeting room, and then take a snapshot with your phone.  If you make money by programming, it's well worth the cost of a decent whiteboard.

If you have another project interrupt the one that has filled up your whiteboard, you may need to resort to the snapshot on your phone, but at least you'll have that in 3 months when the "urgent" project is finished and you have to return to the other one.  If you want to recreate it on your whiteboard then, it would probably only take 15 minutes, and you may find you can improve it a lot in the process, which makes that small investment of time very worthwhile.

3. Make stakeholders aware of the cost of interrupting a project

I find the metaphor of a plane helpful: starting and completing a project is like flying a plane.  If you bail out mid-way through the flight, the plane will not just sit there in the air waiting for you to come back to it, and you need some way to travel from the current project/flight to the next one.  In fact if you're in the middle of a flight from Phoenix to Fargo and you're told that you need to interrupt that flight to take another plane from Denver to Detroit, you'll need to land the first plane in Denver (which is fortunately not far from your flight path—not always the case with real interruptions) and someone has to figure out what to do with the cargo and passengers.  They won't just sit and wait forever.

The point of this for projects is that transitioning from one project to another incurs a large expense of time and leaves a lot of lose ends that have to be dealt with.

In a project there is obviously and inevitably a lot that goes on in your head while you work and not every thought can be serialized to a written medium, and not every iota of those thoughts that are serialized will remain when deserialized.  Although we can partially capture our thoughts in writing, it is very much a lossy format.

The problem (as I see it) is that project managers and other business people think of projects as a series of steps that can often be reordered at will (unless there is an explicit dependency on their Gantt chart) and can be easily distributed amongst people or delayed until it is most convenient for the business.

Anyone who has done any amount of programming knows that software projects cannot be treated like Lego blocks to be moved around any way you like.  I find the metaphor of air travel at least gives stakeholders something concrete that they can think about that clearly cannot be treated as a series of disparate steps to be reordered on a whim.  It at least makes it easy to understand your point that there is a cost to such interruptions.  Of course it is still their decision, but you want to make them aware of this before they interrupt one project to give you another.  Don't be combative, but offer helpful information and the helpful perspective of the developer, ready to do whatever they need from you, but just offering information that they might not be aware of if you don't tell them.

In short:

Write down everything you're about to do, even if you don't think you could ever possibly need it written down.  Even a short pencil beats a long memory.

Brainstorm the big picture on a physical whiteboard that you have persistent access to.

You might avoid project interruptions if you make decision makers aware that there is a cost to such interruptions, and at least you will have set expectations so they know the project will take a bit longer when you resume it.


问:
Omitting "destructors" in C is taking YAGNI too far?
I'm working on a medium embedded application in C using OO-like techniques. My "classes" are .h/.c modules using data structs and function pointers structs to emulate encapsulation, polymorphism, and dependency injection.

Now, one would expect a myModule_create(void) function to come with a myModule_destroy(pointer) counterpart. But the project being embedded, the resources that are instantiated realistically should never be released.

I mean, if I have 4 UART serial ports and I create 4 UART instances with their required pins and settings, there's absolutely no reason to ever want to destroy UART #2 at some point during runtime.

So following the YAGNI (You ain't gonna need it) principle, should I omit the destructors? This seem extremely strange to me but I can't think of a use for them; resources are freed when the device powers-off.

答:
The easiest way I have found to detect memory leaks is to be able to cleanly exit your application. Many compilers/environments provide a way to check for memory that is still allocated when your application exits. If one isn't provided there's usually a way to add some code right before exiting which can figure it out.

So, I would certainly provide constructors, destructors and shutdown logic even in an embedded system that "theoretically" should never exit for ease of memory leak detection alone. In actuality, memory leak detection is even more important if the application code should never exit.


答:
That depends whether or not the language offers something that is ingenious enough that I (representing the customer) am willing to pay money for it.

As a project manager I need to take into consideration:

The time it takes to learn/master that new language.

The efficiency gain (time till delivery) compared to other languages. And does it out-weight the time to learn it?

Does this language solve a problem that can hardly be solved with other languages?

Will this language still be supported in 5 years, should the customer make another request?

The first 3 points apply to every language and especially the first one is a tough to overcome for every new language, because I need to reason the time of very low productivity with something, and that better be a good one.

The 4th point is the one that applies only to closed-source languages, as with those I am dependent on 3rd parties, which might or might not exist in 5 years from now. 5 years earlier from now, mobile apps weren't such a big thing as today, will the language from then adapt to the current situation and allow me to write mobile apps as well? Will it even be compatible to the new requirements? If there is such a requirement for my customer, can I contact the developer of that language and file a request for an upgrade?

If any of those questions is answered with "no", then it can be the best language in the world, I cannot use it. And if I hear that there is a single person who invented this language in his "spare time" and now works as a single-man company, I would be very suspicious about it and rather not use the language, unless I get very solid promises and the language offers something no other allows me to do.


答:
It can. If it is:

good and/or useful enough

if it is applicable easy enough and

if it isn't too expensive

Actually - for starters it should be really strong on 2 first items and very discounted compared to its real worth.

I see most of people complain about evil managers which won't like to pay big cash for it - you never said your friend is asking a fortune for the license. What if he asks for $500 yearly and it saves some company couple of hundreds of working hours every year? Any smart manager would grab it.


答:
You could have a no-op destructor, something like

```<code>  void noop_destructor(void*) {};
</code>```

then set the destructor of Uart perhaps using

```<code>  #define Uart_destructor noop_destructor
</code>```

(add the suitable cast if it is needed)

Don't forget to document. Maybe you want even

```<code> #define Uart_destructor abort
</code>```

Alternatively, special case in the common code calling destructor the case when the destructor pointer function is NULL to avoid calling it.

Title: Omitting "destructors" in C is taking YAGNI too far?

Body:
I'm working on a medium embedded application in C using OO-like techniques. My "classes" are .h/.c modules using data structs and function pointers structs to emulate encapsulation, polymorphism, and dependency injection.

Now, one would expect a myModule_create(void) function to come with a myModule_destroy(pointer) counterpart. But the project being embedded, the resources that are instantiated realistically should never be released.

I mean, if I have 4 UART serial ports and I create 4 UART instances with their required pins and settings, there's absolutely no reason to ever want to destroy UART #2 at some point during runtime.

So following the YAGNI (You ain't gonna need it) principle, should I omit the destructors? This seem extremely strange to me but I can't think of a use for them; resources are freed when the device powers-off.

Body:
You could have a no-op destructor, something like

  void noop_destructor(void*) {};

then set the destructor of Uart perhaps using

  #define Uart_destructor noop_destructor

(add the suitable cast if it is needed)

Don't forget to document. Maybe you want even

 #define Uart_destructor abort

Alternatively, special case in the common code calling destructor the case when the destructor pointer function is NULL to avoid calling it.


答:
Using a source-control system with proper branching and merging strategies, in conjuction with an issue-tracking systems (like Redmine, or GitHub) help you compartmentalize the changes you've made, give them direction, and document your missing 'context' as a natural part of the workflow.

Before you start a code change, make sure there's an 'issue' logged in your issue-tracking system.  That covers the missing "what was I doing" piece of your work.

Create a branch in your source-control system, and make sure your changes in that branch are related ONLY to the afore-mentioned issue.  This will help you isolate changes, and give you a history of the change, answering the question of "where did I leave off?" once you come back to work on it later.

Once you're done with the change, merge it back into your trunk, and close the issue.

Title: How should I remember what I was doing and why on a project three months back?

Body:
I was working on a project three months back, and then suddenly another urgent project appeared and I was asked to shift my attention.

Starting tomorrow, I'll be heading back to the old project. I realize that I do not remember what exactly I was doing. I don't know where to begin.

How can I document a project such that anytime I look back it shouldn't take me more than a few minutes to get going from wherever I left. Are there best practices?