# Common Patterns in Contract

### Withdrawal from Contract

The recommended method of sending funds after an effect is using the withdrawal pattern.

Although the most intuitive method of sending Ether, as a result of an effect, is a direct send call, this is not recommended as it introduces a potential security risk.

This is an example of the withdrawal pattern in practice in a contract where the goal is to send the most money to the contract in order to become the “richest”.

In the following contract, if you are usurped as the richest, you will receive the funds of the person who has gone on to be the new richest:

In the example above, if the Contract is attacked and the withdraw method stuck(for example, msg.sender.transfer(amount) fails), the Contract will keep working.

### Restricting Access

Restricting access is a common pattern for contract.

Note that you can never restrict any human or computer from reading the content of your transactions or your contract’s state. You can make it a bit harder by using encryption, but if your contract is supposed to read the data, so will everyone else.

You can restrict read access to your contract’s state by other contract. This is actually the default unless you declare make your state variables public.

Furthermore, you can restrict who can make modifications to your contract’s state or call your contract’s functions.

The use of function modifier makes thse restrictions highly readable.

### State Machine

Contracts often act as a state machine, which means that they have certain stage in which they behave differently or in which different functions can be called.

A function call often ends a stage and transitions the contract into the next stage.

Function modifiers can be used in this situation to model the states and guard against incorrect usage of the contract.

In the following example, the modifier atStage ensures that the function can only be called at a certain stage, automatic timed transitions are handled by the modifier timeTransitions, which should be used for all functions.

Modifier Order Matters: If atStage is combined with timedTransitions, make sure that you mention it after the latter, so that the new stage is taken into account.

Finally, the modifier transitionNext can be used to automatically go to the next stage when the function finishes.