Everything in computer science ties together in some way, shape or form. Personally I learn best by being able to make connections between things, amd Assignment 2 is no exception.
There are various concepts that come up in assignment 2 - Regexes, Binary Trees, recursion, string manipulation - but that isn't the most interesting part for me. The most interesting part is how it relates to the wider world.
Assignment 2 introduces the concept of taking a set of rules - in this case a regex - that we can't directly work with, and turning them into something we can work with, in this case a tree.
This concept comes back later on when you look at the broader characteristics of programming languages and compilers. What we are essentially doing in assignment 2 is taking a grammar, and generating a parse tree, or a concrete syntax tree from it. This allows us then to check if a sentence or string matches the specified grammar.
It really is interesting how everything comes together at some point, and assignment 2 is yet another example of the importance of first year, introducing concepts that are the foundations of others.
Tuesday, 26 November 2013
Tuesday, 19 November 2013
Encapsulation

Sometimes as a programmer, you don't want your fields and methods modified outside of their own class. Perhaps the best way to solve this, is through information hiding as we discussed in lecture, also known as encapsulation.
In Java, as I'm used to, this is done by declaring your fields with the private keyword. This prevents it from being seen and accessed from outside of the class. In Python we can do something similar by adding an underscore before the name, for example _size will protect it to some extent, however it is only protected by convention.
In order to gain access to these now private variables, we must write what are known as accessor and mutator methods. Accessors returning the value, and mutators changing the value.
The fun and interesting part of all this? Gaining access to these variables without accessors or mutators. There are ways of doing this, my personal favourite is with a technique known as introspection, or reflection.
Reflection allows you to examine and modify an object at runtime, many languages support this. Java for example has a reflection library available for importing and using. Python, as an interpreted language also supports reflection.
The powerful thing about reflection is that it allows you to examine classes, methods, interfaces, and fields at runtime without knowing their names before compilation. It also allows you to instantiate objects and invoke methods without necessarily knowing the names.
So, encapsulation has varying degrees of usefulness, all depending on who is using your code. It can stop many from modifying classes in unintended ways, but to the more knowledgeable programmer, there are always ways around encapsulation.
Subscribe to:
Posts (Atom)