It should be noted that some progamming languages have managed to solve this ugly little issue. I'll use Ruby for the example. The solution entails:
- Remove any form of public data members belonging to an object.
- Make it unnecessary to use parentheses to call methods. This would be for infix-style languages.
- Allow a "writer" (setter) method type. For example, named "bar=".
For example:
class Foo
def initialize
@bar = nil # Create a instance variable
end
def bar
@bar # This is the accessor
end
def bar=(x)
@bar = x # This is the writer
end
end
foo = Foo.new
foo.bar # returns nil
foo.bar = 'blah' # calls "Foo#bar=", returns "blah"
foo.bar # returns "blah"
# This shortens to, for simplification when you need ONLY setting/getting...
class Foo
def initialize
@bar = nil
end
attr :bar # creates "Foo#bar" and "Foo#bar=" methods automatically
end
Given a more
flexible language, doing full
OOP is not
painful. In a purely
OO language (this case, utilizing the nonexistance of
public variables), it won't be as ugly as the
C++ hackery with foo.bar() and foo.set_bar(). (Remember, pointing out
flaws, like non-full-OOP in favor of
C backward compatibility, is not
flamage.)