I am going through the Corda R3 training course and I am making headway, but when asked to create a Paid variable initialized to 0, the answer is:
package net.corda.training.state
import net.corda.core.contracts.Amount
import net.corda.core.contracts.ContractState
import net.corda.core.identity.Party
import java.util.*
/**
* This is where you'll add the definition of your state object. Look at the unit tests in [IOUStateTests] for
* instructions on how to complete the [IOUState] class.
*
* Remove the "val data: String = "data" property before starting the [IOUState] tasks.
*/
data class IOUState(val amount: Amount<Currency>,
val lender: Party,
val borrower: Party,
val paid: Amount<Currency> = Amount(0, amount.token) ):
ContractState {
override val participants: List<Party> get() = listOf()
}
Now I understand that we need to cast the value to type Amount, but why amount.token? I took the solution from:
https://github.com/corda/corda-training-solutions/blob/master/kotlin-source/src/main/kotlin/net/corda/training/state/IOUState.kt
Also, the task was to define it as Pounds, but I cannot figure out how to do so.
I find the reference for Pounds under:
https://docs.corda.net/api/kotlin/corda/net.corda.finance/kotlin.-int/index.html
I just do not understand how I would define the function.
Anyone have any pointers or suggestions for me? This code compiles and the tests pass, but I want to understand why... Thanks!
The token simply indicates what this is an amount of.
So when used here:
val paid: Amount<Currency> = Amount(0, amount.token)
You're taking whatever token was used for the amount parameter e.g. POUNDS, DOLLARS etc and setting the paid Amount to the same token type.
Take a look at how it's done in currencies.kt in Corda
Related
Another question is if there is any better way to write this method?
Public decimal CalculateTotalPrice(List<product> items)
{
decimal totalPrice = 0.m;
foreach(Product p in items)
{
if(p.Offer == "")
calc = new DefaultCalc();
else if(p.Offer == "BuyOneGetOneFree")
calc = new BuyOneGetOneFreeCalc();
else if(p.Offer == "ThreeInPriceOfTwo")
calc = new ThreeInPriceOfTwoCalc()
totalPrice += calc.Calculate(p.Quantity, p.UnitPrice);
}
return totalPrice;
}
You should probably review Polly Want a Message, by Sandi Metz
How to unit test a method that is having multiple object creation in switch statement?
An important thing to notice here is that the switch statement is an implementation detail. From the point of view of the caller, this thing is just a function
Public decimal CalculateTotalPrice(List<product> items);
If the pricing computations are fixed, you can just use the usual example based tests:
assertEquals(expectedPrice, CalculateTotalPrice(items));
But if they aren't fixed, you can still do testing based on the properties of the method. Scott Wlaschin has a really good introduction to property based testing. Based on the logic you show here, there are some things we can promise about prices, without knowing anything about the strategies in use
the price should always be greater than zero.
the price of a list of items is the same as the sum of the prices of the individual items.
if there is any better way to write this method?
You might separate choosing the pricing strategy from using the strategy. As Sandi notes, that sort of construct often shows up in more than once place.
foreach(Product p in items)
{
calc = pricing(p.Offer);
totalPrice += calc.Calculate(p.Quantity, p.UnitPrice);
}
"pricing" would then become something that you pass into this function (either as an argument, or as a dependency).
In effect, you would end up with three different kinds of test.
Checks that pricing returns the right pricing strategy for each offer.
Checks that each strategy performs its own calculation correctly.
Checks that CalculateTotalPrice compute the sum correctly.
Personally, I prefer to treat the test subject as a single large black box, but there are good counter arguments. Horses for courses.
Constructors can not be mocked (at least with free mocking frameworks).
Write tests without mocking as far as your tests run fast and test case setup is not very very complicated.
In your particular case you should be able to write tests without mocking.
Prepare data
var products = new List<Product>
{
new Product { Quantity = 10, UnitPrice = 5.0m, Offer = "" },
new Product { Quantity = 2, UnitPrice = 3.0m , Offer = "BuyOneGetOneFree" },
new Product { Quantity = 3, UnitPrice = 2.0m , Offer = "ThreeInPriceOfTwo" },
}
// prepare expected total
var expected = 57.0m; // 10 * 50.0 + 1 * 3.0 + 2 * 2.0
// Run the test
var actual = CalculateTotalPrice(products);
actual.Should().Be(expected); // pass Ok.
With this approach tests will not depend on implementation details.
You will be able to freely play with designs without rewriting tests every time you change your implementation logic.
The other answers are technically fine, but I would suggest one thing:
if(p.Offer == "")
calc = new DefaultCalc();
else if(p.Offer == "BuyOneGetOneFree")
calc = new BuyOneGetOneFreeCalc();
else if(p.Offer == "ThreeInPriceOfTwo")
calc = new ThreeInPriceOfTwoCalc()
should absolutely go into its own method/scope/whatever.
You are mapping a string to a specific calculator. That should happen in one place, and one place only. You see, first you do that here. Then some method method comes around that needs the same mapping. So you start duplicating.
First, I'm sorry for asking such a dumb question, but quick googling didn't help me much...
I'm a Java delevoper and very new to Groovy. Consider the following code snippet:
class Person {
public String name
}
def jack = new Person()
jack.name = "Jack"
def bob = new Person()
bob.name = "Bob"
def list = new java.util.ArrayList()
list.add(jack)
list.add(bob)
println list.name
Executing it gives the following output (list of name field values for each Person in the list):
[Jack, Bob]
So my question is what the corresponding java code for calling list.name?
My assumption is that it translates to something like:
list.stream().map(person -> person.name).collect(Collectors.toList())
Can somebody explain what exactly happens when i call list.name?
Thanks in advance!
Your code
list.property
is the shortest way to write this. What groovy implies here is the use of the spread operator:
list*.property
(note the * there). And .property could be short here for .getProperty(), for an implicit call to the getter).
So your assumption is correct, that this is the eager collection of the values .getProperty() returns into an ArrayList.
I'm new to Haskell. I'm testing a simple function with Test.Framework:
import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
import Test.HUnit
data Kind = Variable
| Const
| Polymorphic
deriving (Show, Eq, Ord)
calculate :: Int -> Kind -> Float
calculate quantity Variable =
(**2) . fromIntegral $ quantity
calculate _ Const =
10
calculate quantity Polymorphic =
if quantity <= 10 then
10
else
(**2) . fromIntegral $ quantity
prop_ValuePositive quantity kind =
calculate quantity kind
>= 0.0
test_ValueVariable1 =
calculate 1 Variable
#?= (**2) 1
test_ValueVariable2 =
calculate 10 Variable
#?= (**2) 10
test_ValueConst1 =
calculate 1 Const
#?= 10
test_ValueConst2 =
calculate 10 Const
#?= 10
test_ValuePolymorphic1 =
calculate 1 Polymorphic
#?= 10
test_ValuePolymorphic2 =
calculate 11 Polymorphic
#?= (**2) 11
instance Test.QuickCheck.Arbitrary Kind where
arbitrary = Test.QuickCheck.oneof(
[return Variable,
return Const,
return Polymorphic])
main = defaultMain tests
tests = [
testGroup "Value" [
testProperty "Value is positive" prop_ValuePositive,
testCase "Value is calculated right for Variable"
test_ValueVariable1,
testCase "Value is calculated right for Variable"
test_ValueVariable2,
testCase "Value is calculated right for Const"
test_ValueConst1,
testCase "Value is calculated right for Const"
test_ValueConst2,
testCase "Value is calculated right for Polymorphic"
test_ValuePolymorphic1,
testCase "Value is calculated right for Polymorphic"
test_ValuePolymorphic2
]
]
What bothers me is that it's recommended to test pure functions with QuickCheck properties and impure functions with HUnit test cases. But that way, I would have to just repeat the function definition for each of 3 cases (Const, Variable and Polymorphic) in properties to test that the function returns what it's supposed to. That is too much duplication in my opinion:
prop_ValueVariable quantity Variable =
calculate quantity Variable
== ((**2) . fromIntegral $ quantity)
(and so on for all the cases of Kind)
In contrast, in the current code I test only one "obvious" property of function and provide some "sample points" for what the function should return, without actually duplicating the definition (in spirit of unit testing).
What is right approach?
Use properties for testing of all aspects of this function and possibly duplicate its definition in tests
Use properties only for, well, "properties" of what should be returned, but don't duplicate the definition and provide just some unit tests
That property based testing is for pure code and unit tests for impure code is a useful guideline, but not an absolute truth. Unit tests can be useful for pure code, too. I usually start with a unit test, e.g.
describe "parseMarkdown" $ do
it "parses links" $ do
parseMarkdown "[foo](http://foo.com/)" `shouldBe` Link "http://foo.com" "foo"
and then later abstract it to a property
it "parses *arbitrary* links" $
property $ \link#(Link url name) ->
parseMarkdown "[" ++ name ++ "](" ++ url ++ ")" `shouldBe` link
But sometimes I just stick with the unit test because either (a) there is no good property or (b) a property does not increase the test coverage.
On the other hand properties can be useful for impure code, too. You e.g. may want to test your database abstraction with properties
describe "loadUser" $ do
it "retrieves saved users from the database" $ do
property $ \user -> do
saveUser user >>= loadUser `shouldReturn` user
No, of course you are not supposed to duplicate the definition in this way. What would be the point? You may as well simplify the test to prop_trivial q k = calculate q k == calculate q k. The only case when I'd consider it is when you plan to change the way function is calculated in the future and want to check that it still returns the same result.
But if your unit tests are created by just putting values into the function definition and seeing what comes out, they are also not particularly useful either, for the same reason.
Scala noob i'm afraid:
I have the following declared class variable which will the objects I read from the database:
val options = mutable.LinkedList[DivisionSelectOption]()
I then use JPA to get a List of all rows from a table:
val divisionOptions = em.createNamedQuery("SelectOption.all", classOf[SelectOption]) getResultList
/* Wrap java List in Scala List */
val wrappedOptions = JListWrapper.apply(divisionOptions)
/* Store the wrappedOptions in the class variable */
options += wrappedOptions
However, the last line has an error:
Type Expected: String, actual JListWrapper[SelectOption]
Can anyone help with what I am doing wrong? I'm just trying to populate the options object with the result of the DB call.
Thanks
What (probably) is happening is that a JlistWrapper[SelectOption] isn't a DivisionSelectOption, so the method += isn't applicable to it. That being the case, it is trying other stuff, and giving a final error on this:
options = options + wrappedOptions
That is a rewriting Scala can do to make things like x += 1 work for var x. The + method is present on all objects, but it takes a String as parameter -- that's so one can write stuff like options + ":" and have that work as in Java. But since wrappedOptions isn't a String, it complains.
Roundabout and confusing, I know, and even Odersky regrets his decision with regards to +. Let that be a lesson: if you thing of adding a method to Any, think really hard before doing it.
I've defined my ContactDao as follows:
public interface ContactDao extends JpaRepository<Contact, Long> {
/**
* Finds all contacts that the given user has entered where the contact's full name matches {#code name}.
* #param userId The current user's LDAP id.
* #param name The name to search for.
* #return A list of contacts matching the specified criteria.
*/
#Query(" select c from Form as f" +
" inner join f.contacts as c" +
" where f.requestorUserId = :userId" +
" and lower(c.fullName) like lower(:name)" +
" order by lower(c.fullName)")
List<Contact> findUserContactsByUserIdAndName(#Param("userId") String userId, #Param("name") String name);
}
The above is working perfectly, and the SQL generated is what I'd write myself. The problem is that I'd like to add surrounding wild-cards to the :name parameter. Is there any nice way to do this? I've had a look at the Spring Data JPA reference document and I can't find anything regarding wildards and #query.
The following hack works, but is a bit ugly:
and lower(c.fullName) like '%' || lower(:name) || '%'
Does anyone have a better solution?
Thanks,
Muel.
I would also not call it a hack - it's the way JPQL syntax is defined for exactly these problems.
However, there is an alternative using a CriteriaBuilder/CriteriaQuery, but maybe you find it even more complex (but you get compile-time type safety in return).