Philipp Mayer
06/24/2020, 1:37 PMclass Dto(val name: String, val age: Int, val somethingElse: String) {
var signedKey = ""
fun encrypt(shaSign: String): String {
/*do something with all constructor fields*/
return "encryptedString"
}
}
the function encrypt(shaSign: String)
returns an encrypted string by hashing the fields name
, age
and somethingElse
.
I basically just want to set the field signedKey
with the output of that operation.
val dto = Dto("John", 36, "something else")
dto.signedKey = dto.encrypt("someShaKey")
Ofc I could do it like that, but that is really not a good way. I thought a bout a distinct setter which takes a parameter (some sign), executes encrypt
and places the returned value as signedKey
.
How could I achieve that? Thanks ahead!alightgoesout
06/24/2020, 1:40 PMPhilipp Mayer
06/24/2020, 1:49 PMalightgoesout
06/24/2020, 1:52 PMPhilipp Mayer
06/24/2020, 1:56 PMalightgoesout
06/24/2020, 1:58 PMPhilipp Mayer
06/24/2020, 2:00 PMPhilipp Mayer
06/24/2020, 2:01 PMalightgoesout
06/24/2020, 2:05 PMandylamax
06/24/2020, 2:59 PMdata class Dto(
val name:String,
val age:Int,
val somethingElse:String,
val signedKey:String?=null
)
fun Dto.encrypt(shaSign: String) :Dto {
// do something will all constructor fields except signedKey
return copy(signedKey="encryptedString")
}
val signedKey = Dto("John",38,"something else").encrypt("someShaKey").signedKey
Philipp Mayer
06/24/2020, 3:34 PMMatteo Mirk
06/25/2020, 1:41 PMsignedKey
is bad for many known reasons (increased space state and complexity, not being thread-safe, not referentially transparent, etc.). The simplest solution would be to eliminate the field and just let the client decide what to do with encrypt()
output. Otherwise, if you really want to make the signature part of the Dto, this is the most OO and testable way I can think of:
interface DtoSignature {
val key: String
fun encrypt(dto: Dto): String {
return "some hashing using key and dto fields"
}
}
// for test environment
object TestSignature : DtoSignature {
override val key = "test-key"
}
// for prod environment
object ProdSignature : DtoSignature {
override val key = "prod-key"
}
class Dto(
val name: String,
val age: Int,
val somethingElse: String,
private val signature: DtoSignature
) {
val signedKey:String by lazy { signature.encrypt(this) }
}
// usage
var dto = Dto("John", 45, "something", TestSignature)
dto.signedKey // -248748363
dto = Dto("John", 45, "something", ProdSignature)
dto.signedKey. // 909103134