Is there a way to make [incr Tcl] classes friends? - oop

Is there a way to obtain a friendship between classes in incr Tcl?
Consider the code below.
package require Itcl
::itcl::class A {
private {
proc f { } {
puts "==== A::f"
}
}
}
::itcl::class B {
public {
proc g { } {
puts "==== want to be able to call A::f"
}
}
}
I want A::f to be invisible outside A bur functions of B. How can I achieve this?

Itcl doesn't provide friends.
You can hack around this by constructing a call using namespace inscope, like so:
namespace inscope A {A::f}

Related

refer from inner `with` function to higher level `with` function

In my code I have a struct like this
post { req ->
with(req.objectBody<Person>()) {
logger.info { "Attempt to save person $this" }
with(require<SessionFactory>().openSession()) {
save(this#with)
}
}
}
But IDE warns me that there is more than one label with such a name. In this case
save(this#with)
I want to refer to with(req.objectBody<Person>) instance. How to achieve that?
Technically, you can mark lambdas with custom labels and then use labeled this with those labels. such as:
with(foo()) mylabel#{
with(bar()) {
baz(this#mylabel)
}
}
However, to improve readability, instead of with, you can use the let scoping function and provide a name for the parameter:
foo().let { fooResult ->
bar().let { barResult ->
baz(fooResult)
}
}

How to improve my code to show a data array in a table, with TornadoFX?

This is my way to display an array of data:
private val data = observableArrayList(
arrayOf("AAA", "111"),
arrayOf("BBB", "222"),
arrayOf("CCC", "333")
)
class HelloWorld : View() {
override val root = tableview<Array<String>>(data) {
column("name") { cellDataFeatures: TableColumn.CellDataFeatures<Array<String>, String> ->
SimpleStringProperty(cellDataFeatures.value[0])
}
column("value") { cellDataFeatures: TableColumn.CellDataFeatures<Array<String>, String> ->
SimpleStringProperty(cellDataFeatures.value[1])
}
}
}
It works but the code is quite complex. Is there any better way to do it?
(Maybe define a class to hold the data will make it much simpler, but I just want to test some uncommon cases)
Update:
A complete demo project for this: https://github.com/javafx-demos/tornadofx-tableview-array-data-demo
Here is a simpler way of defining your columns:
class HelloWorld : View() {
override val root = tableview(data) {
column<Array<String>, String>("name", { it.value[0].toProperty() })
column<Array<String>, String>("value", { it.value[1].toProperty() })
}
}
That said, using a specialized data structure would yield less headache :)
An alternative approach would be to configure just the cell item type and then a value factory:
column("name", String::class) {
value { it.value[0] }
}
column("value", String::class) {
value { it.value[1] }
}

Style class A + class B AND class A only

I have the following setup at the moment
.classA {
&.classB {
}
&.classC {
}
// some more
}
So every class is dependent on classA. Not requirements changed and I need to have classB,c ... working outside of classA.
However, it's important that it's still connected to classA via &.
I'm looking for something like
.classA, {
... // the comma should indicate classA or nothing
}
The clean way would be
.classB {
&, &.classA {
// style here
}
}
for every class

Specialized Singleton implementation

I am looking for specialized singleton implementation, probably I might be using wrong terminology and hence looking for expert suggestion. Here is my scenario:
There is common code which can be called by ComponentA or ComponentB. I need to push telemetry data from the common code. Telemetry needs to have information that whether this common code get called by ComponentA or ComponentB.
So common code will have just this line of code:
telemetry.pushData(this._area, data);
where this._area tells the telemetry data is getting pushed for which component
I need to push telemetry data from multiple places so it would be good if object got created once and used through out the code lifetime
One option I can think of passing component context to the common code which in mind doesn't look right, hence looking for suggestion what kind of pattern one should use in this case?
This is what I am thinking
// Telemetry.ts file present in shared code
export class Telemetry extends Singleton {
public constructor() {
super();
}
public static instance(): Telemetry {
return super.instance<Telemetry>(Telemetry);
}
public publishEvent(data): void {
if (!this.area) {
throw new Error("Error: Initialize telemetry class with right area");
}
pushtelemetryData(this.area, data);
}
public area: string;
}
// Create Telemetry object from component A
Telemetry.instance().area = "ComponentA";
// Shared code will call telemetry publishEvent
Telemetry.instance().publishEvent(data);
Thanks
It's not a good pattern to use in TypeScript where you would generally inject dependencies.
If you must absolutely do it then you can do it by faking it somewhat:
namespace Telemetry {
var instance : SingletonSomething;
export function push(data: Any) : void {
if (instance == null) {
instance = new SingletonSomething();
}
instance.push(data);
}
class SingletonSomething() { ... }
}
and then you could call
Telemetry.push(data);
You can imitate the singleton pattern in typescript easily:
class Telemetry {
private static instance: Telemetry;
public static getInstance(): Telemetry {
if (Telemetry.instance == null) {
Telemetry.instance = new Telemetry();
}
return Telemetry.instance;
}
...
}
If you have your code in some sort of closure (module, namespace, etc) then you can replace the static member with:
let telemetryInstance: Telemetry;
export class Telemetry {
public static getInstance(): Telemetry {
if (telemetryInstance == null) {
telemetryInstance = new Telemetry();
}
return telemetryInstance;
}
...
}
But then you can also replace the static method with:
let telemetryInstance: Telemetry;
export function getTelemetryInstance(): Telemetry {
if (telemetryInstance == null) {
telemetryInstance = new Telemetry();
}
return telemetryInstance;
}
export class Telemetry {
...
}
At this point, in case you are using some sort of closure, you might ask yourself if you really need the class at all?
If you use this as a module:
// telemetry.ts
export interface TelemetryData {
...
}
export function pushData(data: TelemetryData): void {
...
}
Then you get exactly what you're looking for, and this is more of the "javascript way" of doing it.
Edit
In the telemetry module there's no need to know the users of it.
If the Telemetry.pushData function needs to have information about the object that called it then define an interface for it:
// telemetry.ts
export interface TelemetryData {
...
}
export interface TelemetryComponent {
name: string;
...
}
export function pushData(data: TelemetryData, component: TelemetryComponent): void {
...
}
Then in the other modules, where you use it:
// someModule.ts
import * as Telemetry from "./telemetry";
class MyComponent implement Telemetry.TelemetryComponent {
// can also be a simple string property
public get name() {
return "MyComponent";
}
fn() {
...
Telemetry.pushData({ ... }, this);
}
}
2nd Edit
Because you are using a module system, your module files are enough to make singletons, there's no need for a class to achieve that.
You can do this:
// telemetry.ts
let area: string;
export interface TelemetryData {
...
}
export function setArea(usedArea: string) {
area = usedArea;
}
export function pushData(data: TelemetryData): void {
...
}
Then:
Telemetry.setArea("ComponentA");
...
Telemetry.publishEvent(data);
The telemetry module will be created only once per page, so you can treat the entire module as a singleton.
Export only the functions that are needed.

How to separate models from controllers in testing?

So I wanted to isolate controllers from models in testing so that I could easily figure out stuff if troubles arise. Before, I just hit the endpoints with mock data but it was difficult to troubleshoot because the test runs from the router all the way to the datastore. So I'm thinking maybe I'll just create two versions(MockController vs Controller) for each controller(and model) and use one depending on the value of the mode variable. In a nutshell, this is how I plan to implement it.
const mode string = "test"
// UserModelInterface is the Interface for UserModel
type UserModelInterface interface {
Get()
}
// UserControllerInterface is the Interface for UserController
type UserControllerInterface interface {
Login()
}
// NewUserModel returns a new instance of user model
func NewUserModel() UserModelInterface {
if mode == "test" {
return &MockUserModel{}
} else {
return &UserModel{}
}
}
// NewUserController returns a new instance of user controller
func NewUserController(um UserModelInterface) UserControllerInterface {
if mode == "test" {
return &MockUserController{}
} else {
return &UserController{}
}
}
type (
UserController struct {um UserModelInterface}
UserModel struct {}
// Mocks
MockUserController struct {um UserModelInterface}
MockUserModel struct {}
)
func (uc *UserController) Login() {}
func (um *UserModel) Get() {}
func (uc *MockUserController) Login() {}
func (um *MockUserModel) Get() {}
func main() {
um := NewUserModel()
uc := NewUserController(um)
}
This way I could just skip sql query in the MockUserController.Login() and only validate the payload and return a valid response.
What do you think of this design? Do you have a better implementation in mind?
I would let the code that calls NewUserController() and NewUserModel() decide whether to create a mock or real implementation. If you use that pattern of dependency injection all the way up to the top your code will become clearer and less tightly coupled. E.g. if the user controller is used by a server, it would look something like along the lines of:
Real:
u := NewUserController()
s := NewServer(u)
In tests:
u := NewMockUserController()
s := NewServer(u)
I would try a more slim variant spread over a models and a controllers package, like this:
// inside package controllers
type UserModel interface {
Get() // the methods you need from the user model
}
type User struct {
UserModel
}
// inside package models
type User struct {
// here the User Model
}
// inside package main
import ".....controllers"
import ".....models"
func main() {
c := &controllers.User{&models.User{}}
}
// inside main_test.go
import ".....controllers"
type MockUser struct {
}
func TestX(t *testing.T) {
c := &controllers.User{&MockUser{}}
}
For controller testing consider the ResponseRecorder of httptest package