Skip to content

Commit 7be161c

Browse files
authored
refactor(encapsulation-3.py): Add encapsulation and applies srp
the example wasn't following single responsibility principle by mixing i/o operation with setter/getter. and the increment function volute the encapsulation of the setter.
1 parent 2681e1b commit 7be161c

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

06.Encapsulation/encapsulation-3.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,31 +27,33 @@ def set_val(self, val):
2727
self.val = val
2828

2929
def get_val(self):
30-
print(self.val)
30+
return self.val
3131

3232
def increment_val(self):
33-
self.val = self.val + 1
34-
print(self.val)
33+
self.set_val(self.get_val()+1)
3534

3635

3736
a = MyInteger()
3837
a.set_val(10)
39-
a.get_val()
38+
print(a.get_val())
4039
a.increment_val()
40+
print(a.get_val())
4141
print("Before Break")
4242

4343
# Trying to break encapsulation in a new instance with an int
4444
c = MyInteger()
4545
c.val = 15
46-
c.get_val()
46+
print(c.get_val())
4747
c.increment_val()
48+
print(c.get_val())
4849
print("After Break")
4950

5051
# Trying to break encapsulation in a new instance with a str
5152
b = MyInteger()
5253
b.val = "MyString" # <== Breaking encapsulation, works fine
53-
b.get_val() # <== Prints the val set by breaking encap
54+
print(b.get_val()) # <== Prints the val set by breaking encap
5455
b.increment_val() # This will fail, since str + int wont work
56+
print(b.get_val())
5557
print("Changing DataType")
5658
'''
5759
O/P-
@@ -65,4 +67,4 @@ def increment_val(self):
6567
Traceback (most recent call last):
6668
self.val = self.val + 1
6769
TypeError: can only concatenate str (not "int") to str
68-
'''
70+
'''

0 commit comments

Comments
 (0)