# How to avoid global variables in JuMP

**URL:** <https://discourse.julialang.org/t/how-to-avoid-global-variables-in-jump/101488>\
**Category:** Optimization (Mathematical)\
**Tags:** jump\
**Created:** [July 11, 2023, 3:18pm UTC](https://discourse.julialang.org/t/how-to-avoid-global-variables-in-jump/101488 "2023-07-11T15:18:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![leima0521](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/leima0521/32/51274_2.png) [@leima0521](https://discourse.julialang.org/u/leima0521)\
**Post date:** [July 11, 2023, 3:18pm UTC](https://discourse.julialang.org/t/how-to-avoid-global-variables-in-jump/101488/1 "2023-07-11T15:18:07Z")

</div>

I am reading the [performance tips of JuMP](https://jump.dev/JuMP.jl/stable/tutorials/getting_started/performance_tips/#Read-the-Julia-performance-tips). It says “The most important rule is to avoid global variables”, but I am not sure what it means in the JuMP context and how to implement it.

In the example below, the value of X, Z, K, L are known and defined before JuMP. They are needed to calculate the objective function of the optimization problem. How should I avoid having them as global variables?

```julia
using JuMP, Ipopt

m = Model(Ipopt.Optimizer)

@variable(m, θ[1:4])
@variable(m, δ[1:H])

# X, Z, K, L are known data
mu = @expression(m, X * reshape(θ, (K, L)) * Z')
v = @expression(m, δ .+ mu)
# more arguments..

```

---

<div class="post-metadata">

**Author:** ![sylvaticus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sylvaticus/32/203883_2.png) [@sylvaticus](https://discourse.julialang.org/u/sylvaticus)\
**Post date:** [July 11, 2023, 3:38pm UTC](https://discourse.julialang.org/t/how-to-avoid-global-variables-in-jump/101488/2 "2023-07-11T15:38:33Z")

</div>

You can define them as `const`, but you can also “embed” your model in a function where you pass the parameters (data) of your model as argument of the function and you return the values of the endogenous variables of your model (or whatever of your interest, most likely including the status of the optimisation).  
Something like:

```julia
function find_optimal(H, X, Z, K, L; solver = Ipopt.Optimizer)
   m = Model(solver)
   @variable(m, θ[1:4])
   @variable(m, δ[1:H])
    ...
   optimize!(m)
   return ( θ = value.(θ), δ = value.(δ), status=status(m)
end
```
