OOP MVC structure binding thru interface [closed] - oop

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to build an MVC framework with OOP style.
My idea was to bind controller & service during route session and let function accessible thru interface.
I've encounter an issue when function triggered to service level, it keep returning
"runtime error: invalid memory address or nil pointer dereference"
Route:
var (
testService service.Person = service.NewPerson()
testController controller.TestController = controller.NewTestController(testService)
)
func RouteHandler(rg *gin.RouterGroup) {
routes := rg.Group("/api")
{
routes .GET("/test", testController.Greet)
}
}
Controller:
type TestController interface {
Greet(ctx *gin.Context)
}
type testController struct {
testService service.Person
}
func NewTestController(testService service.Person) TestController {
return &testController{
testService: testService,
}
}
func (controller *testController) Greet(ctx *gin.Context) {
res := controller.testService.Greet()
fmt.Println(res)
ctx.JSON(http.StatusOK, "test")
}
Service:
type Person interface {
Greet() string
}
type person struct {
Person
}
func NewPerson() Person {
return &person{}
}
func Greet() string {
return "Hello"
}

Currently person service embeds the Person, but NewPerson factory method does not assign anything to the Person field, leaving it as nil. When Greet method is invoked on a person struct, the call is delegated to embedded interface Person which is nil and this causes a crash.
Assuming that the person is an "implementation" of the Person interface or more precisely the person should provide the methods with the same signature that is defined by the Person interface, the fix could be as follow:
type Person interface {
Greet() string
}
type person struct {
}
func NewPerson() Person {
return &person{}
}
func (person) Greet() string {
return "Hello"
}
It is worth mentioning that interfaces in Go are implicit. It is possible that your current person declaration is due to habits from other languages, where you have to explicitly indicate that a class (in Go there are no classes) implements some interface.

Related

How to avoid typecasting to subclass when using null object pattern

I have a Value interface with a method to show value as a string.
Usually the value is an integer so IntegerValue implements Value.
Sometimes value is unknown which I use null object pattern for so UnknownValue implements Value.
When the value is actually an integer, it's useful for the client to check whether the value is high enough (IntegerValue.isEnough). This affects how this value is displayed to the user later on. However, if the value is unknown, it doesn't make sense to check if it's high enough--the value is unknown. By the Interface Segregation Principle, UnknownValue should not have an isEnough method.
interface Value {
toString(): string;
}
class IntegerValue implements Value {
private value: number;
constructor(v: number) { this.value = v }
isEnough() { return this.value >= 30 }
toString() { return '' + this.value }
}
class UnknownValue implements Value {
toString() { return 'unknown' }
}
But the client accesses a Value and won't know whether it's an IntegerValue. So I'd have to check and then typecast it.
if(value.toString() !== 'unknown') {
handleInteger(value as IntegerValue) // <-- check if isEnough inside
} else {
handleUnknown(value)
}
I was wondering if there was a design pattern that could solve this with polymorphism, without typecasting.
I was considering the Visitor Pattern like so:
interface ValueVisitor {
handleInteger(v: IntegerValue): void;
handleUnknown(): void
}
class ViewValueVisitor implements ValueVisitor { ... }
class JsonSerializerValueVisitor implements ValueVisitor { ... }
interface Value {
toString(): string;
acceptVisitor(v: ValueVisitor): void;
}
class IntegerValue implements Value {
...
acceptVisitor(v) { v.handleInteger(this) }
}
class UnknownValue implements Value {
...
acceptVisitor(v) { v.handleUnknown() }
}
But the Visitor Pattern violates the Open Closed Principle. I was wondering if there is a better solution.
This answer is very contrived for the problem scope of the default behavior of some value object and its Interface Segregation Principle violation. We can usually afford to sin a little and just type-cast or check the class in the client with value instanceof IntegerValue or value.getType() === 'integervalue'.
But the inherent problem is not confined to only this problem scope. What happens when you have different classes implementing an interface that must be treated differently in the client. When there are more types involved, we may want to follow the SOLID principles to improve cohesion and encapsulation.
Also not sure if this answer is supported by languages other than typescript, but...
I think I got very close with my visitor pattern solution. Just needed one tweak so that the visitor pattern doesn't break the OCP. We can do that with the strategy pattern.
enum HandledTypes {
IntegerValue,
UnknownValue,
...
}
interface ValueHandler {
type: HandledType;
handle(value: Value): void;
}
class ValueVisitor {
handlers: Map<HandledTypes, ValueHandler>;
constructor(handlers: ValueHandler[]) { ... }
handle(key: HandledTypes, v: Value) {
const h = this.handlers.get(key)
h.handle(v);
}
}
// a handler would expect a more specific type
class ViewIntegerValueHandler implements ValueHandler {
readonly type = HandledTypes.IntegerValue;
handle(value: IntegerValue) { ... }
}
interface Value {
toString(): string;
acceptVisitor(v: ValueVisitor): void;
}
class IntegerValue implements Value {
...
acceptVisitor(v) { v.handle(HandledTypes.IntegerValue, this) }
}
class UnknownValue implements Value {
...
acceptVisitor(v) { v.handle(HandledTypes.UnknownValue, this) }
}
Now we can compose a ValueVisitor with all the types it needs to handle within the client.
function doSomething(value: Value) {
const viewValueVisitor = new ValueVisitor([
new ViewIntegerValueHandler(),
new ViewUnknownValueHandler(),
]);
value.acceptVisitor(viewValueVisitor);
}
One problem with this is that I don't see how TypeScript can warn you about providing the incorrect HandledTypes key to ValueVisitor.handle which may lead to a problem at runtime that may or may not throw an error.

Actual type lost on call

Another question on polymorphism in Go, references: Embedding instead of inheritance in Go, https://medium.com/#adrianwit/abstract-class-reinvented-with-go-4a7326525034
Motivation: there is an interface (with some methods for dealing with "the outside world") and a bunch of implementation structs of that interface.
There is a "standard" implementation of some of these methods, where common logic should be put in one place with delegation to (new) methods in the structs-implementing-the-interface ("subclasses" is not a word).
I've read the medium link above and wrote some test code. Alas, it does not work the way I expect, the actual type of a struct is lost when the call on the interface is indirect.
In C++ this is called "based class slicing" and happens when passing a polymorphic class by value. In my Go test code I'm careful to pass by reference, and then Go is not C++ (or Java).
Code: https://play.golang.org/p/lxAmw8v_kiW
Inline:
package main
import (
"log"
"reflect"
"strings"
)
// Command - interface
type Command interface {
Execute()
getCommandString() string
onData(data string)
}
// Command - implementation
type Command_Impl struct {
commandString string
conn Connection
}
func newCommand_Impl(conn Connection, data string, args ...string) Command_Impl {
var buf strings.Builder
buf.WriteString(data)
for _, key := range args {
buf.WriteString(" ")
buf.WriteString(key)
}
return Command_Impl {
conn: conn,
commandString: buf.String(),
}
}
func (self *Command_Impl) Execute() {
log.Printf("Command Impl Execute: %s", reflect.TypeOf(self))
self.conn.execute(self)
}
func (self *Command_Impl) getCommandString() string {
return self.commandString
}
func (self *Command_Impl) onData(data string) {
log.Printf("Command Impl onData: %s", data)
}
// Command - subclass
type Command_Login struct {
Command_Impl
onDataCalled bool
}
func newCommand_Login(conn Connection) *Command_Login {
return &Command_Login{
Command_Impl: newCommand_Impl(conn, "LOGIN", "user#foo.com", "pa$$w0rd"),
}
}
func (self *Command_Login) onData(data string) {
log.Printf("Command Login onData: %s", data)
self.onDataCalled = true
}
// Connection - interface
type Connection interface {
execute(command Command)
}
// Connection - impelementation
type Connection_Impl struct {
}
func newConnection_Impl() *Connection_Impl {
return &Connection_Impl{}
}
func (self *Connection_Impl) execute(command Command) {
log.Printf("Connection execute: %s, %s", command.getCommandString(), reflect.TypeOf(command))
command.onData("some data")
}
func main() {
conn := newConnection_Impl()
command := newCommand_Login(conn)
// I expect command.Execute to preserve actual type of command all the way through
// command.conn.execute(self) and then the callback onData from connection to command
// to use the onData in Command_Login
//
// This does not happen however, the test fails
command.Execute()
// This does preserve actual type of command, but isn't how I'd like to connect
// commands and connections...
//
//conn.execute(command)
if command.onDataCalled {
log.Printf("*** GOOD: Command_Login onData ***was*** called")
} else {
log.Printf("*** ERROR: Command_Login onData ***not*** called")
}
}
There is a Command interface which defines some methods.
There is a Command_Impl struct where I'd like to implement some common code that would further delegate to finer-grained methods in more structs that implement the same interface ("subclass is not a word"), similar to:
https://stackoverflow.com/a/1727737/2342806
The question:
Calling command.Execute() which in turn calls conn.execute(self) ends up "slicing" the Command_Login object and inside Connection.execute it's turned into Command_Impl. As a result, onData interface method defined for Command_Login do not get called.
If I call conn.execute(command) then the right onData does get called, but this is not how I'd like to connect my objects (e.g. Command already has a Connection, but basically what I wrote above about reusing implementation).
In Go terms, I'm trying to come up with a way to delegate implementation by embedding, and have a way to for the delegate to call back into the enclosing type (which fine-tunes the delegate's logic).
Alas, it seems to not be supported by Go (at least I can't find a way) - once you delegate to an embedded struct, your calls stay entirely there in the embedded struct, it "does not know" that it's part of a larger object which may be wanting to override some of the embedded struct's methods.
What about delegating implementation by implementing the Execute interface at the shallowest depth you need?
func (self *Command_Login) Execute() {
self.Command_Impl.Execute()
log.Printf("Command Login Execute: %s", reflect.TypeOf(self))
self.onDataCalled = true
}
https://play.golang.org/p/HvaKHZWIO5W

Golang: Method expressions instances of Object

I'm trying to build a variadic function for a constructor in golang and I've ran into an interesting issue. This function is working...
package main
import "fmt"
type person struct {
name string
}
// This is working, but a really Not how I want to do this
func personConstructor(params ...string) person {
name := "Unnamed Person" // Default name
if len(params) > 0 {
name = params[0]
}
return person{name: name}
}
func main() {
bob := personConstructor("Bob")
}
https://play.golang.org/p/dcAdHEQtYz
And yet this, isn't.
package main
import "fmt"
type person struct {
name string
}
// This isn't working
func (p person) constructor(params ...string) person {
name := "Unnamed Person" // Default name
if len(params) > 0 {
name = params[0]
}
return person{name: name}
}
func main() {
bob := person.constructor("Bob")
}
https://play.golang.org/p/YiTQctu-1A
Any idea as to why this is?
Your problem has nothing to do with variadics.
You need to read and learn about method expressions :
https://golang.org/ref/spec#Method_expressions
package main
type person struct {
name string
}
func (p person) constructor(params ...string) person {
name := "Unnamed Person" // Default name
if len(params) > 0 {
name = params[0]
}
return person{name: name}
}
func main() {
// THIS WORKS
person.constructor(person{},"Bob")
}
This compiles but it makes very little sense to do that in your case. the constructor function expect a person receiver. Whether you put it before like
like person{}.constructor("bob") or after like person.constructor(person{},"bob") doesn't matter. constructor expects a person receiver . constructor method is not a "field of some person namespace", this isn't javascript.
If you want to write a constructor function write a factory without a receiver
func NewPerson(params...string)*Person{
// code
}
that's the idiomatic way to do that in Go.
I suggest you to go through the spec once at least.
The introduction in the Go tour provides a concise answer to your question.
Go does not have classes. However, you can define methods on types.
Your examples assume that the constructor function is defined on the definition of the person struct. This is not the case. A method operates on an instance of a type referred to as a receiver. A constructor is not possible in this mechanism. The established pattern within the Go community is to use a factory function to initialize a struct and is exemplified in your first function definition.
The second example provided is failing because constructor is expecting to be called on an instance of a person which is undefined. If you construct a new instance of a person struct the function behaves as expected.
// https://play.golang.org/p/5XDGSTMVj9
func (p person) constructor(params ...string) person {
name := "Unnamed Person" // Default name
if len(params) > 0 {
name = params[0]
}
return person{name: name}
}
func main() {
// Lets define a new instance of a person struct
p := person{}
// The function, when called on a instance, works as expected
bob := p.constructor("Bob")
fmt.Printf("%+v\n", bob)
}
This illustrates that methods are attributed to an instance of a particular type.

how to deal with embedded interfaces and share data between them

I would like to better understand how to use interfaces, mainly to split code in reusable components and at the same time make it more easy for testing, currently my main question is how to share/get data between the interfaces that belong to a main interface, for example:
https://play.golang.org/p/67CQor1_pY
package main
import (
"fmt"
)
type MainInterface interface {
SubInterfaceA
SubInterfaceB
}
type SubInterfaceA interface {
MethodA()
GetterA(s implementMain)
}
type SubInterfaceB interface {
MethodB()
GetterB(s implementMain)
}
type implementA struct{}
func (ia *implementA) MethodA() { fmt.Println("I am method A") }
func (ia *implementA) GetterA(s implementMain) {
fmt.Println(s.Data)
}
type implementB struct{}
func (ib *implementB) MethodB() { fmt.Println("I am method B") }
func (ib *implementB) GetterB(s implementMain) {
fmt.Println(s.Data)
}
type implementMain struct {
Data string
SubInterfaceA
SubInterfaceB
}
func New(d string) implementMain {
return implementMain{
Data: d,
SubInterfaceA: &implementA{},
SubInterfaceB: &implementB{},
}
}
func main() {
var m MainInterface
m = New("something")
fmt.Println(m.(implementMain).Data)
m.MethodA() // prints I am method A
m.MethodB() // prints I am method B
m.GetterA(m.(implementMain)) // prints "something"
m.GetterB(m.(implementMain)) // prints "something"
}
In the above code, within the methods of struct implementA or implementB how to access the struct elements of the parent holder implementMain that implements MainInterface without passing it as an argument?
with holder struct I mean:
type implementMain struct {
Data string
SubInterfaceA
SubInterfaceB
}
If I am right SubInterfaceA and SubInterfaceB are embedded and help to make the struct implementMain satisfy the MainInterface:
type MainInterface interface {
SubInterfaceA
SubInterfaceB
}
But within the embedded methods of the SubInterfaceA or subInterfaceB what is the best practice to use in order to be available to get the data string?
I created Getter(s implementMain) method and passed the holder struct, but had to cast type:
m.GetterA(m.(implementMain))
I don't know if by satisfying a interface, all the involved interfaces can become part of the same structure scope and if they do, how to get/share data between them or either between its components?, for example besides been available to reach data string how from SubInterfaceA get/access SubInterfaceB

Alternative to load method in Swift

I am working on developing an application in Swift. I wanted to design a system for the application that allowed for loose coupling between objects, and one strategy (which I have used successfully in other languages) was to create something I call an instance factory. It is pretty simple and here is the basic implementation I came up with in Swift:
import Foundation
private var typeGenerators = Dictionary<String, InstanceFactory.GeneratorCallback>()
public class InstanceFactory: NSObject {
public typealias GeneratorCallback = () -> AnyObject!
public class func registerGeneratorFor(typeName: String, callback: GeneratorCallback) {
typeGenerators[typeName] = callback
}
public class func instanceOf(typeName: String) -> AnyObject! {
return typeGenerators[typeName]?()
}
}
The idea is that when an object instance needs access to another object instance, rather than creating that instance outright which would more tightly couple the two objects, the first object would defer to the factory to provide the needed instance by calling the instanceOf method. The factory would know how to provide various instance types because those types would register with the factory and provide a closure that could generate the instance.
The trick is how to get the classes to register with the factory. I had previously made a similar factory in Objective-C and the way I got registration to work was to override the +load method for each class that needed to register with the factory. This worked great for Objective-C, and I figured it could work for Swift as well since I would be restricting the factory to only provide objects that are derived from NSObject. It appeared I got this to work and I spent a significant about of effort designing classes to make use of the factory.
However, after upgrading to Xcode 6.3, I discovered Apple has disallowed the usage of the load class method in Swift. Without this, I am unaware of a mechanism to allow classes to automatically register themselves with the factory.
I am wondering if there some other way to get the registration to work.
What alternatives are available that could allow classes to register with the factory, or what other techniques could be use to accomplish the same kind of loose coupling the factory provides?
I've found a possible solution to your problem after I wanted to register all ViewControllers that would be implementing a certain Protocol in my application and I ran into both this question and a possible answer.
The original was posted here: How to list all classes conforming to protocol in Swift?
I adapted it to Swift 3 and made it a bit more Swift-y and generic:
import UIKit
class ContextRoute: NSObject {
}
#objc protocol ContextRoutable {
static var route: ContextRoute { get }
}
class ContextRouter: NSObject {
private static var storedRoutes: [ContextRoute]?
static var routes: [ContextRoute] {
get {
if let storedRoutes = storedRoutes {
return storedRoutes
}
let routables: [ContextRoutable.Type] = classes(implementing: ContextRoutable.self)
let newRoutes = routables.map { routable in routable.route }
storedRoutes = newRoutes
return newRoutes
}
}
private class func classes<T>(implementing objcProtocol: Protocol) -> [T] {
let classes = classList().flatMap { objcClass in objcClass as? T }
return classes
}
private class func classList() -> [AnyObject] {
let expectedClassCount = objc_getClassList(nil, 0)
let allClasses = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(expectedClassCount))
let autoreleasingAllClasses = AutoreleasingUnsafeMutablePointer<AnyClass?>(allClasses)
let actualClassCount:Int32 = objc_getClassList(autoreleasingAllClasses, expectedClassCount)
var classes = [AnyObject]()
for i in 0 ..< actualClassCount {
if let currentClass: AnyClass = allClasses[Int(i)],
class_conformsToProtocol(currentClass, ContextRoutable.self) {
classes.append(currentClass)
}
}
allClasses.deallocate(capacity: Int(expectedClassCount))
return classes
}
}
I tried it in my application and it works. I clocked it in the simulator and it takes 0.05s for an application that has about 12000 classes.
Consider taking the Swift approach using a protocol instead. I think the solution is actually simpler than the Objective-C approach. There are variations of this with Self constraints which are even better if you have more control over the classes.
// define a protocol to create an instance of a class
protocol FactoryInstantiable {
static func makeFactoryInstance() -> AnyObject
}
// Factory for generating new instances
public class InstanceFactory: NSObject {
public class func instanceOf(typeName: String) -> AnyObject! {
if let ProductType = NSClassFromString(typeName) as? FactoryInstantiable.Type {
return ProductType.makeFactoryInstance()
} else {
return nil
}
}
}
// your class which generally could be defined somewhere else
class MyClass {
var counter : Int
init(counter: Int) {
self.counter = 0
}
}
// extension of your class to conform to the FactoryInstantiable protocol
extension MyClass : FactoryInstantiable {
static func makeFactoryInstance() -> AnyObject {
return MyClass(counter: 0)
}
}