Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #90 Read-only outside

Expose a read-only integer x to the outside world while being writable inside a structure or a class Foo.

local Foo = {}
do
	local x = 0
	Foo.getX = function()
		return x
	end
end
print(Foo.getX()) -- 0
print(x) -- nil
local function Foo()
    local private = {x = 9}
    local mt = {
        __index = private,
        __newindex = function (t, k, v)
            error("attempt to update a read-only table", 2)
        end
    }
    return setmetatable({}, mt)
end

local foo = Foo()
print(foo.x) -- 9
foo.x = 3    -- error: attempt to update a read-only table
package Foos is
      
   type Foo is private;
      
   function X (Self : Foo) return Integer;
      
private
   type Foo is
      record
         X : Integer;
      end record;
      
end Foos;
   
package body Foos is
      
   function X (Self : Foo) return Integer is (Self.X);
      
end Foos;
class Foo final {
  int mX = 0;

public:
  const auto& X() const { return mX; }
};
class Foo
{
	public int x { get; private set; }
}
struct Foo
{
    private int _x;
    int x() {return _x;}
}
class Foo{
  int _x = 0;
  int get x => _x;  
}
module x
  implicit none
  type foo
     integer, private :: x
   contains
     procedure :: readx
  end type foo
contains
  integer function readx(f)
    class(foo) :: f
    readx = f%x
  end function readx
end module x
type Foo struct {
	x int
}

func (f *Foo) X() int {
	return f.x
}
module Foo (Foo, getX) where

import Data.IORef

data Foo = Foo { xRef :: IORef Integer }

getX = readIORef . xRef
const Foo = function Counter () {
  let n = 0
  Object.defineProperty (this, 'value', {get: () => n++})
}
{
  const counter = new Foo ()
  counter.value // 0
  counter.value // 1
}
class Foo {
  #x = 123;
  get x() {
    return this.#x;
  }
}
public class Foo {
    private int x;

    public int getX() {
        return x;
    }
}
class Foo
{
    /** @var int */
    private $x;

    public function getX(): int
    {
        return $this->x;
    }
}
class Foo
{
    /** @var int */
    private $x;

    /**
     * @return int
     */
    public function getX()
    {
        return $this->x;
    }
}
type Foo = class
  private fx: integer;
  public property x: integer read fx;
end;
use Moops;
class Foo {
    lexical_has 'x', isa => Int, accessor => \(my $_x), default => 0;
    method x() { return $self->$_x }
    method increment_x() { $self->$_x(1 + $self->$_x) }
}
class Foo(object):
    def __init__(self):
        self._x = 0

    @property
    def x(self):
        """
        Doc for x
        """
        return self._x
class Foo

  def initialize
    @x = rand(10)
  end

  def x
    @x
  end

end

struct Foo {
    x: usize
}

impl Foo {
    pub fn new(x: usize) -> Self {
        Foo { x }
    }

    pub fn x<'a>(&'a self) -> &'a usize {
        &self.x
    }

    pub fn bar(&mut self) {
        self.x += 1;
    }
}

New implementation...
< >
bbtemp