I am studying design pattern which I can implement to achieve the same purpose as below. However, I am stuck since most of the examples in the net are pretty simple.
I have tried to look at factory method or even strategy method but can't figure out if any of them could be used.
Any suggestion from the guru here?
def checkSomething():
if ...:
return True
else:
return False
def main(mode, state):
if checkSomething() == False:
if mode == False or (mode == True and state == False):
obj_a = Class_A()
return obj_a
else:
Class_B().run()
obj_c = Class_C()
return obj_c
You can return a pair or tuple where first part may be some enum indicating type.
You can create a base class and derive your return class type from common base class. Here, you need to design your program to depend on base class rather than on derived type.
all my personally thoughts
factory pattern opted out here: you are not only creating objects but also making them do stuff
state machine opted out here: there is no state transition here
So I am using the strategy pattern below. But I think you can still use the factory pattern on top so that you further separate the concern of the creation of objects out from the strategy classes.
sort of C# pseudo code here:
interface IClass
{
void Run();
}
class Class_A : IClass { ... }
class Class_B : IClass { ... }
class Class_C : IClass { ... }
interface IStrategy
{
IClass Execute();
}
class StrategyA : IStrategy
{
IClass IStrategy.Execute()
{
var obj_a = Class_A();
return obj_a;
}
}
class StrategyB : IStrategy
{
IClass IStrategy.Execute()
{
Class_B.Run();
var obj_c = Class_C();
return obj_c;
}
}
class DecisionMaker
{
private IStrategy _strategy;
public DecideStrategy(IStrategy strategy) => _strategy = strategy;
public IClass ExecuteStrategy() => _strategy.Execute();
}
main()
{
var decisionMaker = new decisionMaker();
if conditionA
decisionMaker.DecideStrategy(new StrategyA());
else if conditionB
decisionMaker.DecideStrategy(new StrategyB());
return decisionMaker.ExecuteStrategy();
}
Related
I am migrating a project from python to rust, more specifically right now a file which uses the pymemchace library to call the set and get methods.
In order to set and get the cache a class was created, something like this:
class Example:
def __init__(self):
# Create connection with to memcached server
def set_cache(self, ... ):
# Set cache
def get_cache(self, ... ):
# Get cache
Instance = Example()
I know the OOP concepts like classes are implemented a differently on Rust compared to python.
How do you guys think I should approach this ? Build a struct and implement a method using the memcache crate or build a trait and call it as I needed ?
Edit[7/11/2022]:
After reading the comments this is the first model I have for the implementation of the memecache main methods:
rust
extern crate memcache;
use memcache::{Client, MemcacheError};
pub struct CacheManager {
client: memcache::Client,
}
impl CacheManager {
pub fn __ini__() -> Self {
CacheManager {
client: memcache::Client::connect("memcache://localhost:11211").unwrap(),
}
}
pub fn set_cache(&self, key: &str, val: &str, expire: u32) -> bool {
self.client.set(key, val, expire).unwrap();
self.client.replace(" ", "", 100000000).unwrap();
true
}
pub fn get_cache(&self, key: &str) -> Result<Option<String>, MemcacheError> {
self.client.replace(" ", "", 100000000).unwrap();
self.client.get(key)
}
pub fn get_or_set(self, key: &str, val: &str) -> bool {
//If status cache already exist and value is the same then do nothing else set it
let cache_val = self.get_cache(key);
match cache_val.unwrap() {
Some(i) => {
if (i.parse::<i32>().unwrap() - val.parse::<i32>().unwrap()) < 1 {
true
} else {
false
}
}
None => {
self.set_cache(key, val, 86400);
false
}
}
}
}
What do you guys think ?
I will build some testing mod to try it out now.
I had a problem when I started to use Golang after Python. In Python, a variable that is declared inside an if-statement will be visible for a function/method if the statement is inside the function.
from pydantic import BaseModel
class sometype(BaseModel):
"""
A model describes new data structure which will be used
"""
sometype1: str
def someaction(somedata:sometype):
"""
do some action
:param somedata: a sometype instance
:return:
"""
print("%s" % somedata.sometype1 )
def somefunc(somedata:int, somebool:bool, anydata:sometype):
"""
It is a function
:param somedata: some random int
:param somebool: thing that should be True (else there will be an error)
:param anydata: sometype instance
:return:
"""
if somebool==True:
somenewdata=anydata
someaction(somenewdata)
if __name__=="__main__":
print("some")
thedata :sometype = sometype(sometype1="stringtypedata")
somefunc(1, True, thedata)
An IDE only can warn you ("Local variable '...' might be referenced before assignment") that this could not be referenced in some cases (to be precise - there will be no variable named "somenewdata" if the "somebool" be False).
When I tried to do something similar in Go - I couldn't use the variable outside if-statement.
// main package for demo
package main
import "fmt"
//sometype organizes dataflow
type sometype struct {
sometype1 string
}
//someaction does action
func someaction(somedata sometype) {
fmt.Printf("%v", somedata)
}
//somefunc is a function
func somefunc(somedata int, somebool bool, anydata sometype) {
if somebool == true {
somenewdata = anydata
}
someaction(somenewdata)
}
func main() {
fmt.Println("some")
thedata := sometype{"stringtype"}
somefunc(1, true, thedata)
}
This error ("Unresolved reference "..."") will appear in IDE and the code will not compile.
My question was - why does that happening?
I struggled with this problem as I didn't realise that it was implied that the variable which is used inside if-function is not visible for a function.
The answer is simple - you don't need to return the value in this case as you should just fill the value. So, you need to introduce it before the if-statement inside the function, and it will be visible for both: the function and the statement.
// main package for demo
package main
import "fmt"
//sometype organizes dataflow
type sometype struct {
sometype1 string
}
//someaction does action
func someaction(somedata sometype) {
fmt.Printf("%v", somedata)
}
//somefunc is a function
func somefunc(somedata int, somebool bool, anydata sometype) {
//introduce the variable
var somenewdata sometype
if somebool == true {
//fill the variable with data
somenewdata = anydata
}
someaction(somenewdata)
}
func main() {
fmt.Println("some")
thedata := sometype{"stringtype"}
somefunc(1, true, thedata)
}
I'm trying to bind a function that accepts multiple arguments and keyword arguments with PYBIND.
The function looks something like this:
{
OutputSP output;
InputSP input;
if (args.size() == 1)
{
input = py::cast<InputSP>(args[0]);
} else if (args.size() == 2)
{
query = py::cast<OutputSP>(args[0]);
expression = py::cast<InputSP>(args[1]);
}
// TODO: Default values - should be elsewhere?
Flags mode(Flags::FIRST_OPTION);
std::vector<MultiFlags> status({ MultiFlags::COMPLETE });
for (auto& kv : kwargs)
{
auto key_name = py::cast<string>(kv.first);
if (key_name == "flag")
{
mode = py::cast<Flags>(kv.second);
}
else if (key_name == "status")
{
status = py::cast<std::vector<MultiFlags> >(kv.second);
}
}
return method(output, input, mode, status);
}
Where Flags and MultiFlags are defined like this
py::enum_<Flags>(m, "Flags")
.value("FirstOption", Flags::FIRST_OPTION)
.value("SecondOption", Flags::SECOND_OPTION)
.export_values();
py::enum_<MultiFlags>(m, "MultiFlags")
.value("Complete", MultiFlags::COMPLETE)
.value("Incomplete", MultiFlags::INCOMPLETE)
.export_values();
and the wrapper with
m.def("method", &method_wrapper);
Now this should work fine if the call contains
status=[MultiFlags.Complete]
I'm looking for a way to check the type of the kwarg in advance so I could also accept a call that contains
status=MultiFlags.Complete
but can't find anything relevant in PYBIND11 docs. what is the correct way to do this?
Found it.
py::cast throws py::cast_error when casting fails, so I can treat the two options with try-catch:
else if (key_name == "status")
{
try
{
status = py::cast<std::vector<MultiFlags> >(kv.second);
} catch (py::cast_error&)
{
status = { py::cast<MultiFlags>(kv.second) };
}
}
I have a reactjs class called MyDictionary that renders data that a python file sends in. This class returns a dictionary structure. I want to access only a couple of elements from MyDictionary via a separate class, and a different set of elements also from MyDictionary, via a separate class. I tried React.createElement(SomeOtherClass, { as shown below, but this doesn't work... what am I missing?
class MyDictionary extends React.Component {
render() {
return this.props.results.map((result, index) =>
React.createElement(
"div",
{ className: "col-sm-12" },
React.createElement(SomeOtherClass, {
key: result.id,
name: result.name,
index: result.index,
activity: this.props.index + 1,
images: this.props.image_labels
})
)
);
}
}
return MyDictionary;
Looks like your this operator inside the callback function is not what you expect.
The easiest way to resolve this is to create a var to this before your map call.
var _this = this;
Then use _this instead of this inside your callback.
You should also read up on javascript closures.
Edit: render() should return one root element.
class MyDictionary extends React.Component {
render() {
var _this = this;
var children = this.props.results.map((result, index) =>
React.createElement(
"div",
{ className: "col-sm-12" },
React.createElement(SomeOtherClass, {
key: result.id,
name: result.name,
index: result.index,
activity: _this.props.index + 1, // using _this
images: _this.props.image_labels // using _this
})
)
);
return React.createElement("div", null, children);
}
}
return MyDictionary;
I'm currently learning method chaining. I've provided a working python example.
#!/bin/python3
import sys
class Generator(object):
def __init__(self):
return None
def echo(self, myStr):
sys.stdout.write(myStr)
return self
g = Generator()
g.echo("Hello, ").echo("World!\n")
But the Scala version doesn't seem to work, no text is being output.
#!/usr/bin/env scala
final class Printer() {
def echo(msg: String): this.type = {
println(msg)
this
}
}
class Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
Does anybody know why the scala version is not working and why?
You need to compile and call your scala bytecode aferwards. Also, you don't need to specify this.type if your Printer is final, e.g. if your driver.scala file contains:
final class Printer() {
def echo(msg: String) = {
println(msg)
this
}
}
object Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
Then just call:
scalac driver.scala
scala Driver
You should call the main method in your script.
new Driver().main(...) should solve your problem.
Besides, it is the norm to define a main method in an object.
So, instead of
class Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
new Driver().main(...)
I would recommend the following.
object Driver {
def main(args: Array[String]) {
var pr = new Printer();
pr.echo("Hello, ").echo("World!")
}
}
Driver.main(...)
Good luck!