• Effective Communication of Software Requirements

    What is the most effective way to get a customer to clearly explain the requirements for software? Time and again I fail to fully get the full set of requirements from my customers or get an incorrect interpretation. It isn’t that I don’t ask questions or that the customers don’t give me details, but rather it seems that the different perspectives on the requirements lead to many misunderstandings from both parties.

    I’m not trying to nail down every requirement up front - just attempting to get an accurate representation of the requirements I do ask for from the customer. It often seems that a each party understands a particular requirement differently which leads to confusion, frustration, and stalled projects.

    Perhaps using more detailed scenarios where the customer can give a step by step description of how they expect the software to work. Maybe having them give a more visual representation of the software using pictures and flow charts. Perhaps better questions. Maybe a combination of all the above. I wonder if certain methods work better with certain customers?

    Either way, there must be a better way to collect requirements.

  • Scala Named and Default Arguments: A Sticky Situation

    I love named and default arguments. I’ve been using them for years in ColdFusion and find them quite useful. It is a wonder more languages don’t support them. Scala 2.8 has both as new features. Here is an example of the usage.

    class Person( 
      var firstName: String = "Dustin", 
      var lastName: String = "Martin"
    ) 
     
    // Use named arguments 
    val person = new Person( 
      firstName = "John", 
      lastName = "Doe" 
    ) 
     
    // Or use the default arguments 
    val person = new Person 
     
    // Or mix and match the two - lastName uses the default of "Martin" 
    val person = new Person( 
      firstName = "John" 
    ) 
    

    As you can see this is a very simple class with two properties. I’m very fond of these new features and both can serve to simplify your code.

    But not all is well when using named arguments. Lets say you have a class and start off using names arguments for the constructor.

    // Use named arguments 
    val person = new Person( 
      firstName = "John", 
      lastName = "Doe" 
    ) 
    

    No problems yet. But lets say you need to add a custom method for firstName to return “foo” instead of the actual firstName

    class Person( 
      var firstName: String = "Dustin", 
      var lastName: String = "Martin" ){ 
     
      def firstName = "foo" 
    } 
     
    val person = new Person( 
      firstName ="John", 
      lastName = "Doe" 
    ) 
    

    As soon as you run this you find the compiler throwing an error. The problem is that variables and methods share the same namespace. In other words, methods and variables can’t share the same name. Consequently, if a custom method is needed, the variable – in this case firstName – must be renamed. This poses a problem if you have already started using named arguments.

    // The above would need to be... 
    class Person( 
      var _firstName: String = "Dustin", 
      var lastName: String = "Martin"){ 
     
      def firstName = "foo" 
     
    } 
     
    val person = new Person( 
      firstName = "John", 
      lastName = "Doe" 
    ) 
    

    But this still will not work either. The problem is that when the person object is instantiated, the argument firstName is referenced. It no longer exists though. Only _firstName exists. So to fix this we are stuck renaming firstName to _firstName every time a new person object is created. But that seems like a poor solution. We don’t want to have to change all of our code every time we need to update a class.

    So what is the solution to the problem? I’m not sure. Always prefixing variables with underscores or some other character? Not using named arguments? Something else? Right now I’m inclined to simply not use named arguments – at least not for constructor arguments. That way I can change firstName to _firstName and create my custom method without having to update my code. But it would certainly be nice if named arguments could be used in constructors without having to worry about this. Perhaps there is another solution that I’m not aware of. Seeing as how Scala is still a fairly new language, and version 2.8 hasn’t even been officially released, a lot of best practices have yet to be established. It will be interesting to see how the Scala community decides to handle this sticky situation.

  • Thoughts on Event Driven Programming

    What is Event Driven Programming? In the context of ColdFusion, the way I see it is as a way to loosely couple different components from each other by announcing when important moments happen (events) in an application and letting other components register interest and then receive notification via some kind of even manager. This way, components do not really know about each other, only about events that may happen in the system and only have the even manager as it’s dependency rather than any number of related components.

    Does that make sense?

    Just recently I began thinking about event driven programming in the context of ColdFusion. The idea is very appealing to me. Being able to have many of my components be loosely coupled and not having to worry about injecting as many dependencies seems quite nice. Not to mention being able to very easily add new features to an application without having to inject some new component into a bunch of existing components or having to mess with AOP seems lovely.

    The trick though is how to go about creating an event driven architecture (EDA) and then how far to take it in an application. Do you try to use EDA to completely decouple every component or just use it for auditing and similar cross cutting concerns. For instance, is it possible to decouple a DAO from a service so that a service merely announces an event and the DAO registered to listen for that event takes action, saving or querying? It seems that saving is one matter since it doesn’t typically involve any return value. But what about querying? Obviously the DAO would need to return results but how would that be accomplished?

    This leads to another question. What happens if an event fails? Or succeeds for that matter? Is it possible to notify the original component and should I? I have no idea. It seems that might be pretty tricky. Asynchronous events seem much easier to handle.

    The place I really see event driven architectures succeeding though is with things like sending emails, logging, auditing, etc. Crosscutting concerns that need access to many facets of an application. This poses the question though: what about AOP in matters like this? There seems to be some overlap in the two areas. But, as is always the case, it seems some times using an event driven method would be better and likewise, sometimes using an AOP method would be better. I’m curious to know what other uses there are that would be a good fit.

    As with any new thing, it is possible to go completely overboard and overuse it, but I’m leaning to a more subdued approach for the time being. Using events to drive things like auditing seems like good approach for now until I understand it more. I am however, excited to seem what new uses I can come up with.

    I’ve been taking a look at Sean Corfield’s Edmund framework and it is pretty interesting. I’m definitely going to investigate it further, work up some tests, and see how it goes.

  • A Domain Specific Language to Describe a Web Application Model

    The web applications I typically write often have a lot of similarities in them. They usually have a similar architecture, follow the same conventions, use the same libraries, etc. Perhaps another way of putting it would be to say that they follow a similar set of patterns. I have a particular way of programming and my web apps reflect this.

    This however has made me wonder: just how much of an application could be abstracted out and defined within a domain specific language? I have no doubt that much of my apps could be done this way. But how do I go about this? In my reading and tinkering I’ve created small frameworks (or would interpreter be a better word?) that take a DSLs and help to build part of an app for me. What I’m thinking though is on a bit bigger scale: like generating my entire model from a DSL and eventually some views and other portions of my application. But starting from scratch to create a language and framework to build most of my app for me is probably a bit overkill. So, I will just start with my model.

    My model, as is probably the case with others, is fairly formulaic. Of course there is some customization involved but getting the initial SQL, service objects, business objects, etc. created is fairly trivial – just monotonous and time consuming. Which is one reason why you find people using tools like Transfer ORM and Hibernate. Sure, it wouldn’t be that difficult to actually write all the classes that and write all the SQL an ORM creates for you but it definitely would consume a lot of time – time that could be better spent making the application better or getting it done faster (or both). Doing all that manual work also creates a bigger chance that errors will be introduced since you’d be writing so much more code by hand.

    This is why I’ve started getting excited about the possibility of domain specific languages generating my applications or portions of them. The idea of creating a simplified language to allow me to rapidly define my app (or part of it) and cutting out much of the repetitive aspects of development is an exciting idea.

    The type of DSL I’m talking about is called a horizontal DSL if I understand correctly. Horizontal DSLs deal with the technical aspects of app. There are also vertical DSLs that align more with business processes and ideas rather than the technical side of things.

    To start off I’ve worked up a DSL that I hope to start using for the model in my apps. There is still a lot of work to do like creating the framework to transform the DSL into actual code but first I must come up with a usable DSL to define my model in. So far, this is what I have come up with (it is a bit simplified for this blog).

    Note: Much of this DSL I did not originate on my own but from other sources such as Peter Bell’s blog and presentations. His articles and presentations have given me a lot of inspiration in this and much of his examples I have used in this DSL.

    <model>
        <serviceobjects>
            <serviceobject>
                <name>PersonService</name>
                <class>path.to.concrete.service.object.class</class>
                <dataaccessobjects>
                    <include name="PersonDAO" />
                    <include name="OtherDAO" />
                    <include name="AnotherDAO" />
                </dataaccessobjects>
            </serviceobject>
        </serviceobjects>
    
        <dataaccessobjects>
            <dataaccessobject>
                <name>PersonDAO</name>
                <businessobject>person</businessobject>
                <class>path.to.concrete.dao.class</class>
            </dataaccessobject>
        </dataaccessobjects>
    
        <businessobjects>
            <businessobject>
                <name>person</name>
                <pluralname>persons</pluralname>
    
                <pluraltitle>Human Beings</pluraltitle>
                <table>persons_tbl<tbody></tbody></table>
                <idproperty>personID</idproperty>
                <class>path.to.concrete.business.object.class</class>
    
                <properties>
                    <property title="Identification Number" name="personID" datatype="number" columnname="person_id"></property>
                    <property title="Name" name="personName" datatype="string" columnname="person_name">
                        <validationrule name="required" value="true" />
                        <validationrule name="maxLength" value="50" />
                    </property>
                </properties>
            </businessobject>
        </businessobjects>
    </model>
    

    Right now I’d say I’m fairly happy with this DSL. That said, I have very little experience in working with them so only time will tell. I’d love to hear what people’s thoughts on it are though.

  • The Worth of Learning a Language Just for Fun

    I really enjoy learning new programming languages. Actually, I love learning new programming languages. I always have something in my mind that I want to learn. Some things I just want to tinker with a bit and others I want to have a deep understanding of.

    Two languages I’ve been trying out recently are Scala and Flex. Both are very enjoyable languages to use. I’m running into a bit of a problem though. How do I find the motivation to really learn these languages and is it worth it? In the past, I’ve usually just learned languages because I’ve had to for my job. But this time it is just for fun. Sure, someday in the future I might want to get a job using one of these languages but not yet. I just find them to be fascinating languages.

    So the question is this: If I am just learning these for fun, should I invest the time to have a deep understanding of it or just a superficial understanding? Will it benefit me that much? If so, how do I motivate myself to learn it? If one day I want to get a job using either of these languages then how do I get the work experience an employer would be looking for?

    Whatever I do, it is critical for myself and every other programmer to continue learning. Whether that comes from thoroughly learning a single new language, superficially learning a multiple languages, reading books, or simply trying new things in your language of choice, it is vital for our continual improvement.

  • The Cost of Quick and Dirty Programming: Technical Debt

    Why do programmers always make such a big deal about best practices, proper object oriented design, unit testing, and the like? Chances are if you ask somebody who champions these ideas they’ll respond “it makes for higher quality software” or something along those lines. They are probably right about saying it makes for better software. Ideas such as these won’t produce “perfect software” but they definitely improve the chances of better software with easier maintenance.

    I am one of those programmers that believes that unit testing, thoroughly thought out OO design, best practices, etc. contribute to better software. But unfortunately, taking these actions does not come for free. They all take time and energy which translates into money.

    Unit testing is a great example. Writing tests for code can definitely add more time to a project. Possibly quite a bit more time. Many people, myself included, often just ignore testing and just wait for bugs to pop up before they are fixed. It is at times very difficult to find the motivation to write the unit tests and do what I know I should be doing.

    But this view is very short sighted.

    Writing unit tests, while time consuming up front, can dramatically save time, money, and energy later in a project. The reason is because they enable you to find bugs earlier when they are easier to fix which means time and money saved later. It is far easier to fix a bug early in a project soon after it is introduced than when it has been in the system for months and covered but by other layers of code.

    A concept that paints a good picture of the consequences for this quick and dirty approach is called technical debt. The idea of technical debt is related to commonly understood financial debt. It is best explained by Martin Fowler in his post on this metaphor.

    In this metaphor, doing things the quick and dirty way sets us up with a technical debt, which is similar to a financial debt. Like a financial debt, the technical debt incurs interest payments, which come in the form of the extra effort that we have to do in future development because of the quick and dirty design choice. We can choose to continue paying the interest, or we can pay down the principal by refactoring the quick and dirty design into the better design. Although it costs to pay down the principal, we gain by reduced interest payments in the future.

    Doing things quick and dirty, as us programmers often do, has consequences that we frequently ignore or thoroughly take the time to understand. Not writing unit tests or ignoring problematic software designs creates debt that can be difficult to pay down later. Allowing excessive technical debt without reason is a quick way to heavily burden a software project. It has happened to me just as I’m sure it has happened to you.

    But technical debt can sometimes be an OK thing. Sometimes software just needs to get done ASAP or sometimes it is a rarely used or temporary piece of software. In circumstances like this I believe it is ok to take on a certain amount of technical debt.

    This is something I need to remember. Software doesn’t always need to be perfect (if it even can be that). Sometimes it is far more important to just get it done. It often is very tempting to analyze and analyze and analyze in an effort to get that perfect piece of software but never actually get anything programmed. By keeping this metaphor in mind I will hopefully think through how I approach software in the future and think through the consequences of the actions I take.

    Additionally, I like the metaphor of technical debt as a way of working with non-technical users to explain the the time is needed to “do it right” the first time or to pay down the debt accumulated in other phases of the project. Most people have some kind of financial debt so this concept seems like an easy concept for people to understand.

    It also seems useful in explaining to other programmers who may be hesitant to embrace new methodologies and practices. In my work in ColdFusion, I’ve often found other programmers wondering why go through all the work some best practices like unit testing. They think it is too much work and don’t bother. But using this metaphor seems like an effective way to demonstrate the fallacy with that thought process.

    In short, before you program something, take the time to consider technical debt and whether you want to avoid it or accept some in the short term. I plan to do so and hope it will lead me to better think through my actions and consequences in the software I write

  • Monitoring a Form for Changes with jQuery

    JQuery constantly amazes me. Its ability to simplify tasks that ordinarily would have been complicated is truly wonderful. Today I found myself amazed at jQuery’s power yet again.

    First a little background. My coworker had been working on a project which required her to notify users if they were leaving a page with unsaved changes in a form. When she asked me if I had any ideas I researched online to see if anybody else had a solution.

    What I found were some pretty great ideas that allowed me to come up with a solution that is pretty darn cool. The solution uses jQuery’s “:input” selector, “each” function, and “data” function to loop through every form field and store whatever the initial value is. Then it uses “window.onbeforeunload” to check the form before user leaves. The code loops back through all the form fields and checks if the current value is different from the initial value. If so, it notifies the user and give them a chance to stay on the page and save.

    Here is the code.

    $(':input').each(function() { 
        $(this).data('initialValue', $(this).val()); 
    }); 
     
    window.onbeforeunload = function(){ 
        var msg = 'You haven\'t saved your changes.'; 
        var isDirty = false; 
     
        $(':input').each(function () { 
            if($(this).data('initialValue') != $(this).val()){ 
                isDirty = true; 
            } 
        }); 
     
        if(isDirty == true){ 
            return msg; 
        } 
    }; 
    

    Let me break this down a bit.

    The first part of this code finds all form fields: $(':input'). It finds all inputs, textareas, selects, etc. jQuery returns all found elements as an array which I then loop through with the “each” function.

    The next line takes each element in the array and stores a variable called initialValue containing the current value of the form field (remember, the array is a collection of all found form fields on the page) and associates it with that form field. If the “data” method doesn’t make much sense, the jQuery Docs can probably explain it a bit better.

    Next, the function set to the window.onbeforeunload event is run whenever the user tries to leave the page. When run, it once again finds all form elements and compares all current values to the initial values saved earlier. If some changes have occurred, it returns a message to the user.

    One limitation I know of is if new form elements are added to the page after it loads and the initial values of the fields are stored. That could probably be easily remedied but it is just something I haven’t yet done.

    Overall this is a very useful piece of code and is a beautiful example of what can be done with jQuery. I look forward to using this in future projects. As a reference, here are two websites that provided some very useful information about this: CFSilence and My Dog Boris.

  • Easy Object Oriented JavaScript

    I love object oriented programming. Not because I have the crazy misconception that it is the ultimate programming paradigm but because it fulfills my desire to organize, categorize and modularize my code. Consequently I like to bring OO ideas into whatever language I’m working on. Now being primarily a ColdFusion developer I work a lot with JavaScript. But one thing that really took me a while to get a grasp of is making my JavaScript code object oriented.

    I happen to really like JavaScript…mostly. It has some really weird quirks sometimes and parts of it seem poorly designed but overall it is a very powerful and fun language to work with. Its power and quirkiness is very evident when trying to write object oriented code. There seem to be at least three ways to write OO code with JS with all three being completely different. JavaScript just isn’t clear when it comes to OO and doesn’t have any easy to use mechanisms for doing things like inheritance. This is what really tripped me up for a long time. I’d read tutorials and books that would cover the subject (OO) but they’d all do things differently and not explain why they were doing it the way they were.

    Thankfully though I stumbled upon Douglas Crockford’s JavaScript videos this year and opened my eyes on a few things when writing object oriented code. This is what I’ve learned and how I do OO with JavaScript now.

    First thing first, objects. In JS, creating an object is as easy as doing the following:

    myObject = {}; 
    

    Wow, that was easy. No “new” operator or any other mumbo jumbo (is new considered an operator?). Just that one simple line. That simple line creates a singleton object as soon as it is executed. Usually though, you want to have some actually have some functionality in your objects so let’s do that now. There are a couple of ways to do that.

    // OPTION 1 
    myObject1 = { 
        sayHello: function(){ 
            alert("hello world"); 
        }, 
        sayGoodbye: function(){ 
            alert("goodbye"); 
        } 
    } 
     
    myObject.sayHello(); // alerts hello 
    myObject.sayGoodbye(); // alerts goodbye 
     
    // OPTION 2 
    myObject2 = {}; 
     
    myObject2.sayHello = function(){ 
        alert("hello world"); 
    } 
     
    myObject2.sayGoodbye = function(){ 
        alert("goodbye"); 
    } 
     
    myObject2.sayHello(); // alerts hello 
    myObject2.sayGoodbye(); // alerts goodbye 
    

    Both option 1 and option 2 do the same thing but have somewhat different syntaxes. I don’t know if I use either more than the other. It just depends of the circumstances.

    Now one thing you might be wondering is how to have multiple instances of this object? JavaScript doesn’t really have a concept of classes, only objects, which is what this is. Essentially, you’d need to make a new copy of the object every time you wanted a new instance. This is actually very, very easy to do. Simply wrap the object in a function that returns a new instance. Here is how it works.

    function myObject(){ 
        var obj = {}; 
     
        obj.sayHello = function(){ 
            alert("hello world"); 
        } 
     
        obj.sayGoodbye = function(){ 
            alert("goodbye"); 
        } 
     
        return obj; 
    } 
     
    myObject = myObject(); 
    myObject.sayhello(); 
    myObject.sayGoodbye(); 
    

    The wrapper function acts as a class and constructor for the object. Every time the myObject function is called it returns a new instance of your object. You can even have private methods and can pass in constructor parameters.

    function greeter(name){ 
        var obj = {}; 
        obj.name = name; 
     
        // private function 
        function greet(){ 
            alert("hello " + obj.name); 
        } 
     
        obj.sayHello = function(){ 
            greet(); 
        } 
     
        return obj; 
    } 
     
    myObject = greeter("Dustin"); 
    myObject.sayhello(); // alerts "hello Dustin"
    

    Simple and concise. Another nice thing about this method is that inheritance is a breeze.

    function parentObject(){ 
        var obj = {}; 
     
        obj.sayGoodbye = function(){ 
            alert("goodbye"); 
        } 
     
        return obj; 
    } 
     
    function greeter(name){ 
        // This causes the object to "inherit" from parentObject 
        var obj = parentObject(); 
     
        obj.name = name; 
     
        // private function 
        function greet(){ 
            alert("hello " + obj.name); 
        } 
     
        obj.sayHello = function(){ 
            greet(); 
        } 
     
        return obj; 
    } 
     
    myObject = greeter("Dustin"); 
    myObject.sayhello(); // alerts "hello Dustin" 
    myObject.sayGoodbye(); // alerts "goodbye" - sayGoodbye is inherited from parentObject 
    

    What is happening is that greeter calls the parentObject “constructor” to get an object, then modifies it with its own methods, essentially inheriting the functionality from parentObject. Very powerful but very simple. This is only possible because JavaScript objects are modifiable. Many language do not allow objects to be modified with new methods but JavaScript is an exception. Scala, Ruby, and other languages allow this and, in my opinion, this makes for some very concise yet powerful features.

    Unfortunately, this method of doing OO in JS is not something I’ve seen even though it is very straight forward. I suspect that is because object mutability seem to be a rare thing among most mainstream languages like Java. As languages like Ruby gain in popularity I imagine that might change.

  • Old School Batch Programming and Code Generation

    Recently I had the opportunity to do some old school Windows batch file programming at work. At first I was not too interested in using a language (is that even the correct word for it?) as old as DOS, but after I got into the project it was actually rather fun.

    First, a little back story about the project. The company I work for uses many mainframe systems today that it has used for decades. But, like most big companies, it has many modern server systems as well. To use these systems together we often have to move files containing large amounts of data between servers and mainframes. To accomplish this task, a piece of software called Connect:Direct is used.

    Because of the way we used this software, the setup and maintenance was really a pain. First, to setup a file to be moved to/from a mainframe and server, a Connect:Direct “process” has to be setup which consists of a file containing some propriety code to instruct Connect:Direct on what the process should do and how it should run. The file was just text containing some code with a CDP extension. In addition to the CDP file, we had two more simple files per process. One simple batch file so the users of the process can run it simply by double clicking on an icon and a simple text file to be used by the batch file which contains some instructions on which CDP file to use and some variables to use. What that meant was three files per process and a maintenance nightmare. Why a maintenance nightmare you ask? Because a server was recently done away with so every single of our 300 files had to have some details changed.

    Since my coworkers and I knew we would have to change many files we decided to streamline the process a bit. Initially we decided to just combine the batch files into one and have a simple menu so the users could choose the process they wanted from there. Since I was the one writing the batch file I got to work.

    After a bit of work though, I realized that more could be done than merely combining the batch files – we could actually do some code generation. That’s right, code generation with a batch program. Now obviously it couldn’t be too complex seeing how this would be done in a batch program, but a rudimentary form of code generation is possible.

    What I ended up doing was generating the text and CDP files on the fly, executing the Connect:Direct process with them, and then deleting the files afterwards. All the configuring is done in the batch file by setting few variables containing the changing data. What this resulted in was the elimination of 300 files and and extremely easy way to modify processes as well as an easy way to add new processes in the future.

    Before this project I had done a very limited amount of batch file work before. Perhaps what we did could have been done in some other “better” way, but I doubt in the time it took to get this up and running. Batch files might not be very sophisticated, but don’t underestimate there power. Under the right circumstances, they can really prove to be invaluable.

  • Getters and Setters in Scala

    In object oriented programming, getters and setters are something that most would agree have some real world benefits. Unfortunately, they can sometimes be annoying to write. They usually do not consist of a lot of code, but when you have the write the same thing over and over and over it gets old really fast. In my experience, most getters and setters are very much alike so it stands to reason that there must be a “better” way to accomplish the same result.

    In some languages there is support of some kind of “missing_method” syntax that allows the language to dynamically create getters and setters just by looking at the name of the method that doesn’t exist in the object. For example, in ColdFusion, there exists an “onMissingMethod” method that, when included, automatically executes when a method does not exist. This onMissingMethod gets passed the method name that was trying to be accessed and any arguments passed in. Then, by inspecting the method name (lets say, setAge) the method type and property can be determined. From “setAge” it can be determined that the method is a setter and that it should set the property “age”.

    Recently though I’ve done a lot of reading about and playing with Scala and I’ve found that it does things quite a bit different than ColdFusion, Java, and most other languages I’ve seen.

    As a first example, lets see an example of a basic class definition in Scala.

    class Person() { 
     var name = "" 
     var age = 0 
    } 
    

    At first glance you might think that this class only allows you to instantiate a person object but not anything more. But actually, once instantiated, you can set and get the properties by doing the following:

    // Instantiate a person object 
    person = new Person() 
     
    // Print the object's age and name properties 
    println(person.age) 
    println(person.name) 
    

    To set the properties to different values you would do the following:

    // Set the properties to different values 
    person.age = 34 
    person.name = "Dustin Martin" 
    

    Pretty simple so far. You might be thinking to yourself the same thing I thought when I saw an example like this: these aren’t getters and setters! And you are right, that is not what this is. This is simply retrieving the public properties directly from the object. In most languages this would be a very bad idea. What happens when you need to validate the age is in a certain range before it is set? What happens if you want to format the name in a particular way before returning it? In Java or other languages you would be in trouble right about now and probably kicking yourself for not taking the time to write getters and setters. If you wanted to switch from directly accessing the public properties to getters and setters you would either have to find some strange work-around or implement the getters and setters and change any code that access those properties directly to use the getters and setters instead.

    In Scala though, it is no big deal to directly access public properties. You could easily change to using getters and setters by making a couple simple changes to your class.

    class Person() { 
     // Private age variable, renamed to _age 
     private var _age = 0 
     var name = "" 
     
     // Getter 
     def age = _age 
     
     // Setter 
     def age_= (value:Int):Unit = _age = value 
    } 
    

    What this code is doing is pretty simple. First, the variable “age” is renamed to “_age” and made private with the private keyword. Next, the getter is added by the line:

    def age = _age 
    

    This code simply defines a method called “age” and returns the “_age” variable. Scala doesn’t require the return keyword but it would just have easily be written as:

    def age = return _age 
    

    In addition to not requiring the return keyword, Scala doesn’t mandate the use of curly braces around a method body if the body consists of a single expression.

    Next, a setter had to be added to set the new private variable.

    def age_= (value:Int):Unit = _age = value 
    

    This line is a bit more tricky but I’ll explain. First, the method name is “age_=“. The underscore is a special character in Scala and in this case, allows for a space in the method name which essentially makes the name “age =”. The parentheses and contents dictate the value and type that needs to be passed in. The “:Unit” code is equivalent to returning void. The remaining code is setting the “_age” variable to “value”. These things allow the method to be used in the same way as directly accessing the public property.

    person.age = 99 
    

    But wait! Where are the parentheses in this supposed method call?! In Scala, parentheses are usually optional. The previous line could just as easily been written as

    person.age =(99) 
    // OR 
    person.age_=(99) 
    

    As you can see, Scala has some unconventional ideas that provide a solid, well thought out, and an abbreviated syntax to access object properties.