Index
Get the Object Up & Running
Almost any problem has a mix of simple and complex. Start with the simple.
Start with the simple and get your core object working.
As an example, let's say that your problem calls for you to write a class with one instance variable and eight methods. Here is how we might approach it:
- Code up an empty class e.g. Foo {}
- Add in the instance variable (ivar)
- If the ivar needs a getter and setter, add those
- Add a constructor. If the problem calls for multiple constructors, add the simplest one. If it is unspecified, then add a constructor that simply takes the same type as the ivar, and initializes the ivar
- Add a simple "toString" method
- Add a new class FooTester.
- Add a method in FooTester that constructs Foo and prints it using "toString"
- Run the test
Wow! That's good progress.
👍🏽
Add More Behaviors to the Object
Next steps:
- Find the simplest method in the write-up
- Code it
- Add a test for it in FooTester
- Run the test
- Repeat for all the methods in the write-up that you are clear on (come back to the others later).
Attacking the More Complex Methods
Now let's start to tackle more complex parts of the problem. Similar how we took a "divide and conquer" above, we can do similar with any more complex method.
Example problem: We have a method named "myMethod" that receives one method parameter (an index) which is an "Integer" object (not "int"). The index may be positive, negative, or null.
Let's assume that our instance variable is named "list".
The positive index (zero to list size minus one) we understand right away.
So our approach is:
- First add the method header (return type, method name, parameters). We know our param is "Integer index".
- For our first pass we'll assume a positive index (zero or greater)
- Code it up
- Test and run as before
Good progress!
👍🏽
Now let's tackle the negative index. Let's assume that -1 really means the index (list size-1), -2 really means the index (list size - 2), etc.
Here we go:
- We want to change "myMethod" as little as possible
- We add a helper (sister) method named "convertIndexToRegular".
- Then from "myMethod" all we need to do is call that method with the method param. No other changes are needed!
😊
The algorithm for "convertIndexToRegular" is not too bad:
- The method paramer for this method is also "Integer" index
- Assign the param to a local variable "i"
- If "i" is greater or equal to zero, simply return "i"
- Else convert it to a regular index using the list "size" as described above and return it.
That's All!
🤸🏽
Tackling Generics
If there is a generics aspect to the problem, and we are clear on how the generics should be coded, then we may as well code it in right away. However, if we're not clear on the generics, first code up the object without generics to get it up and running, and add the generics after words. Here is some guidance....
Java Fundamentals